String Pool Objects

Can you clarify me how many objects will be created in the following case and why? I am a little confused by this.

String s1 = "cat";

String s2 = "cat";

String s3 = "c"+"at";

String s4 = new String("cat");

String s5 = "kitty"+"cat";

String s6 = new String("kittycat");

String s7 = s5;

String s8= new String(s5); // Newly Added in this Question
+4
source share
2 answers

Let's take a look step by step:

String s1 = "cat";
String s2 = "cat";

These two will be the same constant pool entry created in your class file by the javac compiler. When this class is loaded, this line (along with all the other lines of the constant pool) will be automatically interned, so it will also be merged with other lines "cat"in other classes.

String s3 = "c"+"at";

: , javac. , s1 s2. JLS, 15.18.1:

String (§12.5), (§15.28).

String s4 = new String("cat");

. Java , new , , . , ( , ), == , JIT- . == System.identityHashCode, , .

"cat", , , s1, s2 s3.

String s5 = "kitty"+"cat";

s3: javac "kittycat" . -, , .

String s6 = new String("kittycat");

s4: . s6 == "kittycat" , false.

String s7 = s5;

s5, .

, : 4 , 2 . : , (.. Java- ), .

+8

user3360241 - ... , , ... , .

Set<Integer> set = new HashSet<Integer>();

set.add(s1.hashCode());
set.add(s2.hashCode());
set.add(s3.hashCode());
set.add(s4.hashCode());
set.add(s5.hashCode());
set.add(s6.hashCode());
set.add(s7.hashCode());

System.out.println("size :: "+set.size());
0

All Articles