Home > Back-end >  About intern () method of doubt, please advise.
About intern () method of doubt, please advise.

Time:10-27

 
HelloJava String a=new String (" ");
String a1=Anderson ntern ();
System. The out. Println (a==a1);//false


String String b=new String (" ") + new String (" Tests ");
String b1=b.i ntern ();
System. The out. Println (b==b1);//true


Inconsistent results these two examples, is it because the new String (" helloJava) after this step, would bring helloJava literal automatically into a constant pool, so the back intern () can get a constant pool of reference, namely a1, and a just heap references, so false?
Example 2 b StringTests final object in the heap, only is not constant pool, so the intern () returns or object in the heap, so true?
Is this understanding the great god, when you give advice or comments, thank you,

Where wrong hope great god glad!

CodePudding user response:

First of all,
For String a=new String (" helloJava) ", "helloJava" will be in the constant pool, and then use this constant pool object in the heap initializes a new object is assigned to a, so a and constant pool object is not the same as
The second
String a1=Anderson ntern (); For intern method (you can refer to doc document), if the constant pool does not exist, then put a constant pool, and returns the constant pool of reference assigned to a1, due to the constant pool has been around for "helloJava" (a statement), so the intern didn't put a constant pool, but returned directly "helloJava" references, so a1 constant reference object, a reference to the heap object
So a==
a1 is false
For String b=new String (" String ") + new String (" Tests "); Constant pool into the "String" and "Tests" two objects, but there is no in the constant pool "StringTests" (because there is not a constant is "StringTests", it is just a product of variables together, so not in the constant pool), but in the heap generation "StringTests" object, make references to the object b
So
String b1=b.i ntern (); Intern here method found no "StringTests" in the constant pool, and then put b in the constant pool (b is equivalent to reference the constant pool objects at this time, because he had been on a constant pool), and then put the constant pool object reference is assigned to b1 (b1 is also cited the constant pool objects) at this time, b and b1 are cited the constant pool object,
So b==b1 is true

So the intern will put objects in the constant pool, feel a constant pool before calling intern has had the same object, if you have, then, that the original object in the heap or the heap, and constant pool object is irrelevant,==false; If not, then it's put into the constant pool of objects in the heap, so objects in the heap into a constant pool of objects, so==is true


  • Related