How + internally works on Strings in JAVA

I read from blogs that internally java uses StringBuilder to concatenate String when we use the + operator. I just checked it and found some weird outlets.

public class StringDemo { public static void main(String[] args) { String a = "Hello World"; String b = "Hello World"; String c = "Hello"; String d = c + " World".intern(); String e = new StringBuilder().append(String.valueOf(c)).append(" World").toString().intern() ; String f = new StringBuilder(String.valueOf(c)).append(" World").toString().intern(); System.out.println(a == b); // Line 1 Expected output true System.out.println(a == d); // Line 2 Output is false System.out.println(a == e); // Line 3 Output is true System.out.println(a == f); // Line 4 Output is true } } 

So, I use the + operator to execute two strings c and "World" , and then use the intern () method to move String to the pool for string d .

According to my understanding, java uses StringBuilder, so now I use StringBuilder to concatenate String and use the intern () method for strings e and f . Therefore, if both equivalent addresses of both lines must be the same, but the output of line 2 does not match lines 4 and 5.

Thanks in advance for your valuable feedback.

+5
source share
1 answer

How + internally works in JAVA

Here is my post on the same, let me read the compiler version: how string concatenation works in java.

And go to your code inside

 System.out.println(a == d); 

It should be only false .

According to your understanding, you expect true . No. Your understanding is wrong. There is a clear difference between

  String d = c + " World".intern(); 

AND

  String d = (c + " World").intern(); 

In the first line, only "World" received internment, and the second line of "Hello World" received internment

When you execute (c + " World").intern() , you will see the output true .

+10
source

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


All Articles