JAVA Syllabus
QUESTIONS & ANSWERS

How two strings are compared in Java?

There are several ways to compare two strings in Java.

  1. Using the equals() method:
    The equals() method compares the contents of two strings and returns true if they are equal, i.e., if they have the same characters in the same order. It returns false otherwise. Here's an example:
    String str1 = "Hello";
    String str2 = "World";
    String str3 = "Hello";
    
    System.out.println(str1.equals(str2)); // false
    System.out.println(str1.equals(str3)); // true
    
  2. Using the == operator:
    The == operator compares the references of two objects. If the references are equal, the operator returns true. Otherwise, it returns false.
    String str1 = "Hello";
    String str2 = "Hello";
    
    System.out.println(str1 == str2); // true
    

    However, it is important to note that the == operator does not compare the contents of the strings. It only compares the references. This means that the following code will also print true:

    String str1 = new String("Hello");
    String str2 = new String("Hello");
    
    System.out.println(str1 == str2); // false
    

    Even though the strings str1 and str2 have the same content, they are not equal because they are different objects.

  3. Using the compareTo() method:
    The compareTo() method compares two strings lexicographically. It returns an integer value that indicates the relationship between the two strings. The return value is:

    -> Negative if the first string is lexicographically less than the second string. 
    -> Zero if the two strings are equal.
    -> Positive if the first string is lexicographically greater than the second string.
    String str1 = "apple";
    String str2 = "banana";
    String str3 = "apple";
    
    System.out.println(str1.compareTo(str2)); // negative value
    System.out.println(str1.compareTo(str3)); // 0
    System.out.println(str2.compareTo(str1)); // positive value
    

    It's important to note that the compareTo() method is case-sensitive, meaning uppercase letters are considered to have a different value than lowercase letters.

  4. Using the compareToIgnoreCase() method:
    The compareToIgnoreCase() method is similar to the compareTo() method, but it ignores case differences.

    For example, the following code will print 0:
    String str1 = "Hello";
    String str2 = "hello";
    
    System.out.println(str1.compareToIgnoreCase(str2)); // 0
    

    This is because the values of str1 and str2 are equal, even though they differ in case.

    These are the basic methods to compare strings in Java. Additionally, Java provides other methods like equalsIgnoreCase(), startsWith(), endsWith(), etc., that allow you to perform more specific string comparisons based on your requirements. In general, the equals() method is the most commonly used method for comparing strings.

29/05/2023, 6:25 am Read : 289 times