+ 1

Can someone explain more about using '==' in java to compare regular variables?

Someone commented in the tutorial that when comparing regular variables e.g. int or double, it is checking the values of the variables are the same. But why it is 'false' in this case I see in challenge: String s1 = "You cannot challenge me!"; String s2 = "You cannot"; String s3 = s2 + " challenge me!"; System.out.println(s1 == s3) //false While i tried that if s2= "You cannot challenge me!"; then s1==s2 Can someone explain the differences?

2nd Jan 2020, 9:30 PM
Elise Ray
Elise Ray - avatar
3 Réponses
+ 1
Coder Kitten if '==' compare the reference (memory location) of string literals instead of content, then why would s2 == s1 becomes true WHEN I change s2 to "You cannot change me!" (same content as s1)
3rd Jan 2020, 10:44 AM
Elise Ray
Elise Ray - avatar
+ 1
Elise Ray string literals are stored in the string constant pool and it cannot contain any duplicates. So when you say s2==s1 it means both are pointing to the same string constant hence the reference is same. Consider a string constant pool with these 2 constants. Now your s1 is pointing to "You cannot change me!" and if you again assign the same string to s2 then the reference of s1 is returned and stored in s2 since s1 is already holding that string constant. It is like s2=s1. | I'm a constant | s1->| You cannot change me! |<-s2 ----------------------------------------
3rd Jan 2020, 11:00 AM
Avinesh
Avinesh - avatar
0
Since all the 3 of them are String Objects the == does reference checking and as we know that the JVM does not allow a creation of a duplicate string literal in the string constant pool. So when- String s3 = s2 + " challenge me!"; First the reference of s2 is assigned to s3 which is created in heap and then the other part of the string is added which is on the string constant pool. So s1 and s3 in no way have the same reference so s1==s3 returns false. Try making the s2 as final which will make it a constant and then s1==s3 will return true.
3rd Jan 2020, 2:16 AM
Avinesh
Avinesh - avatar