How does the intern work in the following code?

String a = "abc"; String b = a.substring(1); b.intern(); String c = "bc"; System.out.println(b == c); 

The question may be silly, as the old man has no significant use here, but I got confused about this fact why the results are b == c true .

At

 String b = a.substring(1) 

String b references to an object having "bc"

Does b.intern literal "bc" in the String Constant pool, even if it is, how did b==c result in true ?

+5
source share
2 answers

String b = a.substring(1); returns an instance of a string that contains "bc" , but this instance is not part of the string pool (only literals are interned by default, a string created with new String(data) and returned from methods such as substring or nextLine not interned by default) .

Now when you call

 b.intern(); 

this method checks if the String string contains a string equal to the one stored in b (which is "bc"), and if not, it puts that string there. So sine there is no line representing "bc" in the pool, the line from b will be placed there.

So now the row pool contains "abc" and "bc" .

Because of this, when you call

 String c = "bc"; 

the string literal representing bc (the same as in link b ) will be reused from the pool, which means that b and c will contain the same instance.

This confirms the result of b==c , which returns true .

+5
source

Take a look at the document String#intern() method

When the intern method is called, if the pool already contains a string equal to this String object, as determined by the equals (Object) method, the string from the pool is returned. Otherwise, this String object is added to the pool and a reference is returned to this String object.

Now follow the comments

  String b = a.substring(1); // results "bc" b.intern(); // check and places "bc" in pool String c = "bc"; // since it is a literal already presented in pool it gets the reference of it System.out.println(b == c);// now b and c are pointing to same literal 
+5
source

Source: https://habr.com/ru/post/1234728/


All Articles