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);
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.
source share