+ 1
Why I am getting false
check out this code https://code.sololearn.com/cdV7DBtUZyqq/?ref=app public class Program { public static void main(String[] args) { String s1 = "Mississippis"; s1=s1+'s'; String s3="Mississippis"+'s'; String s2 ="Mississippiss"; System.out.println(s1); // Print Mississippiss System.out.println(s2); // Prints Mississippiss System.out.println(s3 == s2);// prints true System.out.println(s1 == s2); // Prints "false", why s1 and s2 should point at same object as s1 is present in string pool
5 Answers
+ 11
that's because they are references of different objects.
variables in java are always objects(except primitives), the name you give is a reference.
So using == you are testing if they are the same obj but they aren't!
use equals() instead, like @Cool Codin said.
+ 10
That is why you don't use == for comparing two strings!
Java has a built-in method for this: equals()
so..
s1.equals(s2); // it prints true
+ 3
@ Jamie Thanks I got little bit but still as s1 is changed it points to a different object , so during instantiation of s2 , it search for that string in the string pool and it is already present so it doesn't need to create a new string object.