Java - Compare String values for equality

== on String

You should not use == operator to test two strings for equality. For example,

String str1 = new String("Hello"); 
String str2 = new String("Hello"); 
boolean b = (str1 == str2); // Assigns false to b 

Demo

public class Main {
  public static void main(String[] args) {
    String str1 = new String("Hello"); 
    String str2 = new String("Hello"); 
    boolean b; /*from  ww w.j ava  2 s.  co m*/
      
    b = (str1 == str2); // Assigns false to b 

    System.out.println(b);
  }
}

Result

Note

The new operator always creates a new object in memory.

str1 and str2 refer to two different objects in memory.

str1 == str2 evaluates to false even if they have the same value.

When == operator is used with reference variables, it compares the references of the objects its operands are referring to.

To compare the text represented by the two String variables str1 and str2, use the equals() method of the String class.

  
b = str1.equals(str2); 
b = str2.equals(str1); 

Demo

public class Main {
  public static void main(String[] args) {
    String str1 = new String("Hello"); 
    String str2 = new String("Hello"); 
    boolean b; /*from w  w  w  . j av  a  2s  .co  m*/
    b = str1.equals(str2); 
    System.out.println(b);
    b = str2.equals(str1); 

    System.out.println(b);
  }
}

Result

Related Topic