Because == tests whether the two Strings are the same object. If you need to compare the content, use
it means both object are pointing to same memory location or what ?
When u creates
String s1 = "String";
String s2 = "String";
and then compares s1==s2 then it returns true . It means that both are pointing to same memory location.
But in above exampe scenario is differen. That is where I am confused . I really don't know how it is woriking ?
In this case the strings are located in the String pool and are the same reference.
It stops working, when you use
String s1 = new String("String"); String s2 = new String("String"); System.out.println(s1 ==s2);
Just stop using == when comparing Strings, unless you wnat to compare the objects.
I am also not willing to comapre content. I want to know what it checks exactly with such kind of scenario.
== checks whether the references are the same. equals() checks the content.
what exactly == means ? does it check the references are pointing to same memory location or not ?
So when S1 is created , it has memory address where it is pointing to and when "String' is created at run time , it should look in constant pool whether it is created or not and as per my understanding , JVM will create temporary reference for "String" and then equality of reference should happen , i.e. s1 == t1 , but it is not happening , so what is going on behind the scene ?
> not happening
You are confusing a text literal, the quoted text string, with the 'new String' expression. The fact that they look like they should be the same "reference" does not make them the same. They are different.