Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 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 might be foolish as intern has no major usage here, still I am confused about the fact, why does b == c results true.

When

String b = a.substring(1)

is executed, String b references to object having "bc"

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

like image 522
Arijit Dasgupta Avatar asked Oct 28 '15 19:10

Arijit Dasgupta


1 Answers

String b = a.substring(1); returns string instance which contains "bc" but this instance is not part of string pool (only literals are by defaults interned, string created via new String(data) and returned from methods like substring or nextLine are not interned by default).

Now when you invoke

b.intern();

this method checks if String Pool contains string equal to one stored in b (which is "bc") and if not, it places that string there. So sine there is no string representing "bc" in pool it will place string from b there.

So now String pool contains "abc" and "bc".

Because of that when you call

String c = "bc";

string literal representing bc (which is same as in b reference) will be reused from pool which means that b and c will hold same instance.

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

like image 52
Pshemo Avatar answered Sep 19 '22 08:09

Pshemo