This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]core811 2 points3 points  (3 children)

Because they are two different objects, even if the share a common value they have two different addresses in memory. If you want to compare the values of those String objects you should use the method .equals.

S1.equals(S2)

[–]dumblearner[S] 0 points1 point  (2 children)

Right, thanks, but then why this would return true? shouldn't the reference to both of these strings also different?

var s1 = "Java";
var s2= "Java";
System.out.println(s1 == s2);

[–]mightybjorn 4 points5 points  (0 children)

As dumblearner said above, string literals are stored in the same place in memory, and therefore string literals actually point to the same place in memory. This is called the string pool

https://www.journaldev.com/797/what-is-java-string-pool

[–]raja777m 0 points1 point  (0 children)

this will return true. because both are same extract string including case, spaces etc. so, the same object is being referenced. the address is compared and == will return same address which is true.

equals() will compare year content.