Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Constant Pool mechanism

Tags:

java

string

Can anyone explain this strange behavior of Strings?

Here's my code:

String s2 = "hello";
String s4 = "hello"+"hello";
String s6 = "hello"+ s2;

System.out.println("hellohello" == s4);
System.out.println("hellohello" == s6);

System.out.println(s4);
System.out.println(s6);

The output is:

true
false
hellohello
hellohello
like image 956
Hitesh Avatar asked Dec 02 '22 16:12

Hitesh


2 Answers

You need to be aware of the difference between str.equals(other) and str == other. The former checks if two strings have the same content. The latter checks if they are the same object. "hello" + "hello" and "hellohello" can be optimised to be the same string at the compilation time. "hello" + s2 will be computed at runtime, and thus will be a new object distinct from "hellohello", even if its contents are the same.

EDIT: I just noticed your title - together with user3580294's comments, it seems you should already know that. If so, then the only question that might remain is why is one recognised as constant and the other isn't. As some commenters suggest, making s2 final will change the behaviour, since the compiler can then trust that s2 is constant in the same way "hello" is, and can resolve "hello" + s2 at compilation time.

like image 169
Amadan Avatar answered Dec 16 '22 16:12

Amadan


"hello" + s2 works like this:

  • An instance of the StringBuilder class is created (behind the scenes)
  • The + operator actually invokes the StringBuilder#append(String s) method
  • When the appending is done, a StringBuilder.toString() method is invoked, which returns a brand new String object. This is why "hellohello" == s6 is actually false.

More info:

  • How do I compare Strings in Java?
  • How Java do the string concatenation using “+”?
like image 43
Konstantin Yovkov Avatar answered Dec 16 '22 17:12

Konstantin Yovkov