navneet chandra
navneet chandra

Reputation: 63

Both strings should be equal?

String s1 = "learn";
String s1 = s1+"Java";

now s1 is pointing to "learnJava" string right ?

String s2 = "learnJava";

if(s1 == s2) is false. WHY ?

s2 should point to same "learnJava" as its already present in StringConstantPool(s1).

Upvotes: 1

Views: 299

Answers (2)

Mrab Ezreb
Mrab Ezreb

Reputation: 440

This is an issue that came up for me as well.
A char: 'a' is a primitive
A Character: new Character('a') is an object
A String: "a" is an object
The reason that "learnJava" != "learnJava" is that they are different objects.
So, in order to check if two strings are equal, you have to do:

String s1 = "learnJava";
String s2 = "learnJava";
s1.equals(s2) > true

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502016

s2 should point to same "learnJava" as its already present in StringConstantPool.

Nope - the string pool is only used for constant strings unless you call intern.

So the string pool contains "learn", "Java" and "learnJava"... but s1 refers to a string not in the string pool, because the concatenation is performed at execution time.

If you had a compile-time constant expression, it would be different:

String s1 = "learn" + "Java"; // Constant expression
String s2 = "learnJava";
System.out.println(s1 == s2); // true, guaranteed

Or if you want to keep your execution-time concatenation:

String s1 = "learn";
s1 += "Java";
s1 = s1.intern();
String s2 = "learnJava";
System.out.println(s1 == s2); // true

In general though, just don't compare strings with ==... it's almost always a bad idea.

Upvotes: 12

Related Questions