Public classtestcase{StaticString AB = "AB"; StaticString Geta () {returnA; } StaticString Getab () {return"AB"; } Public Static voidMain (string[] args) {//1String _ab =NewString ("AB"); System.out.printf ("Ab==_ab%b\n", ab==_ab); //2String S1 = "a" + "B"; System.out.printf ("Ab==s1%b\n", ab==S1); //3String s2 = geta () + "B"; System.out.printf ("Ab==s2%b\n", ab==S2); //4System.out.printf ("Ab==getab ()%b\n", ab==Getab ()); //5String s3 =NewString ("AB"); System.out.printf ("Ab==s3%b\n", ab==S3); }}
Output Result:
Ab==_ab false
AB==S1 true
Ab==s2 false
Ab==getab () True
AB==S3 false
First output:
Although there is a string "AB" inside the constant pool, _ab is a reference to another string object in memory.
The second output:
Compiler optimizations, because the + around is an explicit character constant, so the plus operator does not request a new string variable, but points to the constant pool of "AB". If there is no "ab" in the constant pool, then the plus operator adds "AB" to the constant pool
The third output:
The compiler does not optimize because the compiler considers the left operand to be string rather than a string constant (who calls it not a dominant 2333). The plus operator will request a new string.
Fourth output:
Since AB and Getab () point to the same string constant "AB", the address must be the same.
Fifth output:
It's like repeating the first one. 233
Traps for string constant pools in Java