Why are the results of of str == str.intern() for StringBuilder using append or not different?
Asked Answered
M

1

5

All.I have a java code snippet like this:

 String a = new StringBuilder("app").append("le").toString();
 System.out.println(a.intern() == a);
 String b = new StringBuilder("orange").toString();
 System.out.println(b.intern() == b);

and this java code will output true,false. I wonder why. Thanks All.

Madonnamadora answered 8/10, 2016 at 7:7 Comment(0)
K
11

In both cases, StringBuilder.toString() creates a new string.

In the first case, String.intern() finds that there's no string "apple" in the intern pool, so adds the provided one to the pool and returns the same reference - which is why it prints true.

In the second case, String.intern() finds that there's already a string "orange" in the intern pool, so returns a reference to that - which is a different reference to b, hence it prints false.

Note that if you had a line before the start of this code of:

System.out.println("apple");

then you'd see false from the first comparison too, for the same reason.

Koenraad answered 8/10, 2016 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.