Persistent pool string engine

Can anyone explain this strange behavior Strings?

Here is 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);

Conclusion:

true
false
hellohello
hellohello
+4
source share
4 answers

You need to know the difference between str.equals(other)and str == other. The first checks if the two lines have the same content. The latter checks to see if they are the same object. "hello" + "hello"and "hellohello"can be optimized as the same line at compile time. "hello" + s2will be computed at runtime and therefore will be a new object other than "hellohello"even if its contents are the same.

EDIT: - 3580294, , . , , , , , - . , s2 final , , s2 "hello" is "hello" + s2 .

+6
String s2 = "hello";
String s4 = "hello" + "hello"; // both "hello"s are added and s4 is resolved to "hellohello" during compile time (and will be in String pool)
String s6 = "hello"+ s2; // s6 is resolved during runtime and will be on heap (don't apply Escape analysis here)

,

System.out.println("hellohello" == s4); // true
System.out.println("hellohello" == s6);  // false
+5

"hello" + s2 :

:

+5

String s4 "hellohello" - . - true :

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

s6 , s2. "hellohello" s6 . - false :

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

But if you declare it s2as final , which makes the constant a s2constant, you get trueinstead of falsethe string System.out.println("hellohello" == s6);, because now the compiler can put the string s6, since it depends on constant values, and the links to "hellohello" s6will be equal to each other.

+2
source

Source: https://habr.com/ru/post/1546807/


All Articles