Problems with Java String

I ran the following program,

String firstString = "String"; String secondString = "String"; String thirdString = new String("String"); System.out.println(firstString == secondString); System.out.println(firstString == thirdString); System.out.println(firstString.intern() == thirdString); System.out.println(firstString.intern() == thirdString.intern()); System.out.println(firstString.intern().equals(thirdString.intern())); System.out.println(firstString == thirdString); 

and my result was

 true false false true true false 

I found out that the jvm pool is the pool with the same contents as the strings. It is right? If thats true, then why not firstString == thirdString returns false? Is jvm a pool of string initialization only: "", and not with a new operator?

+7
source share
4 answers

The union applies only to string literals - so firstString and secondString are actually the same object - where, as in thirdString , you explicitly requested to create a new object on the heap.

I recommend reading the section on string literals in the spec .

It provides additional information on how and when strings are grouped.

Also note these bullets at the end of the section:

  • Literal strings in the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  • Literal strings in different classes in the same package represent references to the same String object.
  • Literal strings in different classes in different packages also represent references to the same String object.
  • Lines computed by constant expressions (§15.28) are evaluated at compile time, and then processed as if they were literals.
  • Lines computed by concatenation at runtime are created and therefore different.
+6
source

For firstString and secondString, the JVM will look for a pool of strings and return a "String" link.

For the third String, the JVM will not look up the string pool and will only create a String object on the heap.

For OneString.intern (), the JVM will look for the link in the string pool, add OneString to the string pool if OneString does not exist in it and return the link.

+2
source

thirdString NOT from the pool. This is not a string literal; you dynamically created it using the new operator.

secondString on the other hand, is taken from the pool (you assign it a string literal), so the same object is assigned to both firstString and secondString .

0
source

"firstString == thirdString" returns false.

The intern method "returns the canonical representation for the string object." If you assigned an intern string:

 thirdString=thirdString.intern(); 

last "firstString == thirdString" returns true

-one
source

All Articles