0

How does Java decide when a new String should be created?

I assume it depends on the specific JVM implementation/ compiler, but I thought the results of this test were interesting enough to ask the question:

class A { public String test = "test";}
class B { public String test = "test";}
...
public static void main (String[] args)
{
    String test = "test";
    System.out.println(test == "test");                // true
    System.out.println(test == new String("test"));    // false
    System.out.println(new A().test == new B().test);  // true
}
flakes
  • 21,558
  • 8
  • 41
  • 88

1 Answers1

3

String literals are always interned, this is not directly platform-dependent.

Except when using the explicit initialization idiom through the constructor (new String(someString)).

In that case, a new Object is created, which causes the reference equality operator (==) to return false in your example.

Needless to say, always use equals for reliable String value comparison, but I suspect this falls out of your question's scope.

Mena
  • 47,782
  • 11
  • 87
  • 106
  • so apart from specifically calling the constructor, there's no guarantee that objects are unique? Is there a possibility that something like `"test" == "test!".substring(0,4)` would return true? – flakes Mar 02 '16 at 17:05
  • 1
    @flkes it depends. For your specific example with `substring` the answer is **maybe**, and you can find out why by looking at the source for `String#substring`: it will return a `new String(value, beginIndex, subLen)` (so `false`), unless the beginning index is `0` and the last index is equals to the original `String`'s length. In that last case, it returns the same object. So: `System.out.println("test" == "test".substring(0,"test".length()));` will actually return `true` :) – Mena Mar 02 '16 at 17:08