Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
user2376271 Avatar asked Oct 08 '16 07:10

user2376271


People also ask

What is string intern () When and why should it be used?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

What is the purpose of Intern () method in the string class?

intern() The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

Can I append string to StringBuilder?

append() method is used to append the string representation of some argument to the sequence.

What is the difference between appending a string to a StringBuilder and concatenating two strings with a operator?

concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object. + operator creates a new String object every time irrespective of the length of the string.


1 Answers

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.

like image 110
Jon Skeet Avatar answered Oct 13 '22 01:10

Jon Skeet