Confusion about java pool string literal and string concatenation

that's it, I ran into a problem while writing the code below

String hello = "Hello";
String str5 = "Hel" + "lo";
String str8 = "Hel";
String str9 = "lo";
String str10 = str8 + str9;
System.out.println("str10==hello?" + (str10 == hello)); 
System.out.println("str5==hello?" + (str5 == hello));
System.out.println("str10==str5?" + (str10 == str5));

then I ran my code and the console printed this

str10 == hello ? false
str5 == hello ? true
str10 == str5 ? false

It really confused me. why is the second seal TRUE, but the first seal is FALSE ?? in my understanding of a string literal pool, when a certain string and the JVM checks if the pool contains this string, if not, put the string in the pool. In my code, the hello variable exists in the string pool, Helo "and" lo "also in the pool, my question is

  • if the pool contains the result of combining Helo "and" lo ".
  • str5 str10s "=="? str5 str10 " Hello", ? ( "==" , )

my jdk : 1.6.0_29
IDE: Intellij Idea 11.2

- ?

+5
4

, . JLS.

JLS # 3.10.5:

(§15.28), "", , String.intern.

JLS # 15.28 , . , ( "Hel" "lo" ), , , .

, , str8 str9 , true :

final String str8 = "Hel";
final String str9 = "lo";
+7

:

String hello = "Hello";

"Hello" - , hello, -

String str5 = "Hel" + "lo";

"Hel" + "lo" 2 , hello, , , , hashcode

String str8 = "Hel";
String str9 = "lo";

str8 + str9 - , hello, -

String str10 = str8 + str9;
System.out.println("str10==hello?" + (str10 == hello)); 
System.out.println("str5==hello?" + (str5 == hello));
System.out.println("str10==str5?" + (str10 == str5));

==, - . , .

string_1.equals(STRING_2)

string_1 == string_2

. ,

. ( == vs equals() Java?):

equals() "" String ( ) , (2) String . - (2) String String, ! (2) (2) String, . "" ( : ) String, .

, "==" , , String. String, "true".. duh. , , String ( String "", String ), "false".

0
String hello = "Hello";       // at compile time string is known so in String Constant Pool

String str5 = "Hel" + "lo";   // at compile time string is known so in String Constant Pool same object as in variable hello

String str8 = "Hel";          // at compile time string is known so in String Constant Pool

String str9 = "lo";           // at compile time string is known so in String Constant Pool

String str10 = str8 + str9;   // at runtime don't know values of str8 and str9 so in String Constant Pool new object different from variable hello

str10 == hello ? false        // as str10 has new object and not the same as in hello

str5 == hello ? true          // both were created at compile time so compiler know what the result in str5 and referenced the same object to str5 as in hello

str10 == str5 ? false         // str10 is a different object, hello and str5 are referenced same object as created at compile time.
0
source

If u compare two strings, use string.equalsnotstring1 == string2

try:

System.out.println("str10==hello?" + (str10.equals(hello));
-1
source

All Articles