Java string comparison == VS equ
Code:
public class TestString {
public static void main(String[] args) {
String str1 = "aaaa";
String str2 = "abab".replace('b', 'a');
String str3 = new String("aaaa");
String str4 = "aaaa";
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3: " + str3);
System.out.println(str1 == str2);
System.out.println(str1 . equals(str2));
System.out.println(str1 == str3);
System.out.println(str1.equals(str3));
System.out.println(str1 == str4);
System.out.println(str1.equals(str4));
}
}
Output:
str1: aaaa
str2: aaaa
str3: aaaa
false
true
false
true
true
true
This is because:
The “==” operator compares the references of two objects in memory. It returns true if both objects point to exact same location in memory. Remember that Strings are immutable in Java, so if you have a String variable str1 with a value of “aaaa” and then you create another variable str4 with value “aaaa”, rather than creating a new String variable with same value, Java will simply point str4 to same memory location that holds the value for str1.
In this scenario str1==str4 will return true because both str1 and str4 are referencing the same object in memory.
However, if you create a new variable using the String constructor, like String str3=new String(“aaaa”); Java will allocate new memory space for str3. Now although str1 and str3 have exact same value, str1==str3 will return false because they are two distinct objects in the memory.
The equals method compares the text content or the value of two string variables. If both variables have exact same value, equals() will return true, otherwise it will return false.
So, str1.equals(str2) , str1.equals(str3), and str1.equals(str4) will all return true.