String str1 = "abc:5";
String str2 = "abc:" + str1.length();
String str3 = "abc:" + 5;
System.out.println(str1==str2);
System.out.println(str1==str3);
Output of the program is : false true
But I don't understand why?
==
operator will compare reference only
.equals()
will compare the values.
in your case
str1==str2
// compares the two references, which are different.
had it been, str1.equals(str2)
, it would have compared the values, which will return true
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.The “==”
operator compares the objects’ location(s) in memory
The “equals” method
The Java String class actually overrides the default equals()
implementation in the Object
class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.
Here str1 = "abc:5"; is located in constant pool of string and str2 is concatenated with 2 different object with new operator. So both str1 and str2 are referring to different object. That's the reason it is showing false.
The ==
operator is used for only reference variables in java. For example if you are comparing characters a1
and a2
you can use the ==
operator because the char
type is highlighted in most IDEs in Java. To check if two Strings are equal to each other you can use .equals()
or .equalsIgnoreCase()
to compare the Strings. This is because Strings are objects, not primitives, and require their own method in the class to test if Strings are the same.
For the first System.out.println();
statement, you would use System.out.println(str1.equals(str2));
or System.out.println(str1.equalsIgnoreCase(str2));
.
For the second System.out.println();
statement, you would use System.out.println(str1.equals(str3));
or System.out.println(str1.equalsIgnoreCase(str3));
.