November 10, 2020
A brief memorandum on how to use the equals method for comparing strings and ==
.
==
and epuals
I will get into the main subject immediately. Use the ==
operator when comparing whether two values are equal in a primitive type such as int or char. In case of reference type such as String type, compare with equals method.
When comparing with ==
in the case of reference type such as String type, compare whether the reference destination is the same </ b>, and not compare whether the reference destination value is the same.
Let's actually run it with the sample code.
Sample code
public static void main(String[] args) {
//Initialize the String type variables str1 and str2 with the same string
String str1 = "hello";
String str2 = "hello";
if(str1 == str2)
System.out.println("str1=str2 (==Compare with) ");
else
System.out.println("str1≠str2 (==Compare with) ");
//Add the same string
str1 += "!";
str2 += "!";
if(str1 == str2)
System.out.println("str1=str2 (==Compare with) ");
else
System.out.println("str1≠str2 (==Compare with) ");
if(str1.equals(str2))
System.out.println("str1=str2 (Compare with equals) ");
else
System.out.println("str1≠str2 (Compare with equals) ");
}
Execution result
str1=str2 (==Compare with)
str1≠str2 (==Compare with)
str1=str2 (Compare with equals)
When str1 and str2 of String type variables are initialized with the same string and the same string is added, false
is returned when compared with==
, and true
is returned when compared with the equals method. I'm returning. The String type is treated as a pseudo primitive type at the time of declaration and initialization, but is used as a reference type when a character string is added. Therefore, even if the values are the same, the reference destination is different, so comparing with ==
returns false.
Comparison of basic type and comparison of reference type [Quick learning Java] Difference between ”==” and “equals” (explains how to deny)
Recommended Posts