Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the results of of str == str.intern() for these strings different?

public static void main(String[] args) {
    String str1 = new StringBuilder("计算机").append("软件").toString();
    System.out.println(str1.intern() == str1);
    String str2 = new StringBuffer("ja").append("va").toString();
    System.out.println(str2.intern() == str2);
}

Results:

 true
 false   

First one prints true, and the second prints false. Why are the results different?

like image 362
side Avatar asked Aug 14 '15 01:08

side


People also ask

What does string intern () method do?

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.

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 use of the intern () method hard?

The intern() method creates an exact copy of a string that is present in the heap memory and stores it in the String constant pool if not already present. If the string is already present, it returns the reference.

What is the use of intern () method show with small example?

Java String intern() method explained with examples This method ensures that all the same strings share the same memory. For example, creating a string “hello” 10 times using intern() method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance.


1 Answers

The difference in behavior is unrelated to the differences between StringBuilder and StringBuffer.

The javadoc of String#intern() states that it returns

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

The String created from

String str2 = new StringBuffer("ja").append("va").toString();

is a brand new String that does not belong to the pool.

For

str2.intern() == str2

to return false, the intern() call must have returned a different reference value, ie. the String "java" was already in the pool.

In the first comparison, the String "计算机软件" was not in the string pool prior to the call to intern(). intern() therefore returned the same reference as the one stored in str2. The reference equality str2 == str2 therefore returns true.

like image 50
Sotirios Delimanolis Avatar answered Oct 17 '22 20:10

Sotirios Delimanolis