vvekselva
vvekselva

Reputation: 823

Java String problems

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 output was

true
false
false
true
true
false

I learnt that the jvm pools string with same content as same strings. Is that right? If thats true then why not the firstString == thirdString return false? Does jvm only pool the string only initialized with :"" and not with new operator?

Upvotes: 7

Views: 1444

Answers (4)

RonK
RonK

Reputation: 9652

The pooling relates to string literals only - so firstString and secondString are actually the same object - where as in thirdString you explicitly asked for a new object to be created on the heap.

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

It provides more information on how and when strings are pooled.

Also, take note to these bullets at the end of the section:

  • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
  • Strings computed by concatenation at run time are newly created and therefore distinct.

Upvotes: 6

Simon J. Liu
Simon J. Liu

Reputation: 827

For firstString and secondString, JVM will lookup the string pool and return the reference of "String".

For thirdString, JVM will not lookup the string pool and will only create a String object in heap.

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

Upvotes: 2

Roberto Mereghetti
Roberto Mereghetti

Reputation: 627

"firstString == thirdString" returns false.

The method intern "returns a canonical representation for the string object." If you assign the interned string:

thirdString=thirdString.intern();

last "firstString == thirdString" returns true

Upvotes: 0

amit
amit

Reputation: 178521

thirdString is NOT from the pool. It is not a string literal, you dynamically created it with the new operator.

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

Upvotes: 0

Related Questions