简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM