Does string pool behave differently when used with concat?

String s1 = "Hello".concat("World");
String s3 = new String("HelloWorld"); //Line-2
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false

If I delete Line-2 and compare s1 == s2, it will return true. Can someone explain to me what exactly happens in the row pool after Line-2? And what happens on every row in the heap and in the constant pool?

From what I understand, s1 will create "HelloWorld" in the persistent pool. But still s1 == s2 is false?

+4
source share
1 answer

If you have this:

String s1 = "Hello".concat("World");
String s2 = s1.intern();
System.out.println(s1 == s2); //true

... s1.intern()adds s1to the pool and returns s1, because there is no equivalent string in the pool. So naturally s1 == s2.

But when you have this:

String s1 = "Hello".concat("World");
String s3 = new String("HelloWorld"); //Line-2
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false

... "HelloWorld" ( ). s1.intern() , s1. s1 == s2 .

, :

String s1 = "Hello".concat("World");
String sx = "HelloWorld";
String s3 = new String(sx);
String s2 = s1.intern();
System.out.println(s1 == s2); //false
System.out.println(s1 == s3); //false
System.out.println(s2 == s3); //false
System.out.println(s1 == sx); //false
System.out.println(s2 == sx); //true

sx - , .

, , s1 "HelloWorld"

, concat . s1 , s1.intern(), . "-2" , , "-2" : "HelloWorld" .

+10

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


All Articles