Question

I know that in case of String class, you must normally use .equals() where comparing two strings, like:

String s1 = "123";
String s2 = "123";
String s3 = "1234";
s1.equals(s2); // true
s1.equals(s3); // false

but, i've tried today this code:

s1 == s2; // true, but different references so had to return false
s1 == s3; // false

so, is something changed in java? does now string use standard comparable implementation when using == ?

Was it helpful?

Solution 2

s1 == s2; // true, but different references so had to return false

No, both are referring same String literal object "123" in String literal pool. Hence returned true, when you checked with ==

If you use String s = "Some" to create object, the object is referred from String Constant Pool.

If you use the new operator to create the object, then in heap String objects will be created.

OTHER TIPS

The expression "123" is not a String instance creation expression; it denotes a reference to a singleton String instance representing that string value in the string pool.

Therefore the values of your variables s1 and s2 are in fact the same.

== checks only for the object referred by the reference.

String s1 = "123";
String s2 = "123";

Here s1 and s2 pointing the same string pool object "123"

String s1 = new String("123");
String s2 = new String("123");

s1.equals(s2); true , because this approach is not checking the values rather the objects but s1==s2; false in this case.

If you assign a literal to a String variable, it will point to the internalized String found in the String pool. But if you instantiate a String by new String("123") you get a new one. If you like to avoid this, using only singletons from the String pool, you have to call new String("123").intern(), which puts the new instance into the pool, or if an equal String is already in the pool, returns its reference. From the JavaDoc:

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the #equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top