String s1 = new StringBuilder().append("").append("").toString();
System.out.println(s1.intern() == s1);
String s2 = new StringBuilder().append("ja").append("va").toString();
System.out.println(s2.intern() == s2);
output results
true
false
I can understand the first true, but why is the second false? the book says that "java" appeared before stringbuilder.tostring (). After I check it on javap
Constant pool:
-sharp1 = Methodref -sharp14.-sharp27 // java/lang/Object."<init>":()V
-sharp2 = Class -sharp28 // java/lang/StringBuilder
-sharp3 = Methodref -sharp2.-sharp27 // java/lang/StringBuilder."<init>":()V
-sharp4 = String -sharp29 //
-sharp5 = Methodref -sharp2.-sharp30 // java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
-sharp6 = String -sharp31 //
-sharp7 = Methodref -sharp2.-sharp32 // java/lang/StringBuilder.toString:()Ljava/lang/String;
-sharp8 = Fieldref -sharp33.-sharp34 // java/lang/System.out:Ljava/io/PrintStream;
-sharp9 = Methodref -sharp35.-sharp36 // java/lang/String.intern:()Ljava/lang/String;
-sharp10 = Methodref -sharp37.-sharp38 // java/io/PrintStream.println:(Z)V
-sharp11 = String -sharp39 // ja
-sharp12 = String -sharp40 // va
-sharp13 = Class -sharp41 // TestPool
-sharp14 = Class -sharp42 // java/lang/Object
-sharp15 = Utf8 <init>
-sharp16 = Utf8 ()V
-sharp17 = Utf8 Code
-sharp18 = Utf8 LineNumberTable
-sharp19 = Utf8 main
-sharp20 = Utf8 ([Ljava/lang/String;)V
-sharp21 = Utf8 StackMapTable
-sharp22 = Class -sharp43 // "[Ljava/lang/String;"
-sharp23 = Class -sharp44 // java/lang/String
-sharp24 = Class -sharp45 // java/io/PrintStream
-sharp25 = Utf8 SourceFile
-sharp26 = Utf8 TestPool.java
-sharp27 = NameAndType -sharp15:-sharp16 // "<init>":()V
-sharp28 = Utf8 java/lang/StringBuilder
-sharp29 = Utf8
-sharp30 = NameAndType -sharp46:-sharp47 // append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
-sharp31 = Utf8
-sharp32 = NameAndType -sharp48:-sharp49 // toString:()Ljava/lang/String;
-sharp33 = Class -sharp50 // java/lang/System
-sharp34 = NameAndType -sharp51:-sharp52 // out:Ljava/io/PrintStream;
-sharp35 = Class -sharp44 // java/lang/String
-sharp36 = NameAndType -sharp53:-sharp49 // intern:()Ljava/lang/String;
-sharp37 = Class -sharp45 // java/io/PrintStream
-sharp38 = NameAndType -sharp54:-sharp55 // println:(Z)V
-sharp39 = Utf8 ja
-sharp40 = Utf8 va
-sharp41 = Utf8 TestPool
-sharp42 = Utf8 java/lang/Object
-sharp43 = Utf8 [Ljava/lang/String;
-sharp44 = Utf8 java/lang/String
-sharp45 = Utf8 java/io/PrintStream
-sharp46 = Utf8 append
-sharp47 = Utf8 (Ljava/lang/String;)Ljava/lang/StringBuilder;
-sharp48 = Utf8 toString
-sharp49 = Utf8 ()Ljava/lang/String;
-sharp50 = Utf8 java/lang/System
-sharp51 = Utf8 out
-sharp52 = Utf8 Ljava/io/PrintStream;
-sharp53 = Utf8 intern
-sharp54 = Utf8 println
-sharp55 = Utf8 (Z)V
Excuse me, where is the literal amount of the original "java"?