Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java [String a = new test ] vs [String b = test ]

  1. Dec 1, 2011 #1
    Java [String a = new "test"] vs [String b = "test"]

    Can you tell me what is the difference between the two?
    What is going on behind the scenes?
  2. jcsd
  3. Dec 1, 2011 #2

    Filip Larsen

    User Avatar
    Gold Member

    Re: Java [String a = new "test"] vs [String b = "test"]

    Assuming that you meant String("test") in the first case, it will create a new string instance. Thus, if you have two such strings they would always be different instances even if the strings themselves are equal, that is

    Code (Text):

    String a = new String("test");
    String b = new String("test");
    assert a != b;
    assert a.equals(b);
    In the second case you are referencing a so-called interned string instance (see [1] and [2]). This means that String a = "test"; is equivalent to String a = new String("test").intern(); which means that if you have two equal text literals (or other interned strings) they will reference the same instance, that is

    Code (Text):

    String a = "test";
    String b = "test";
    assert a == b;
    assert a.equals(b);
    In most circumstances you will want to use the later approach to initialize strings from string literals in Java as multiple uses of the same literal will result in only one string instance being used.

    [1] http://en.wikipedia.org/wiki/String_interning
    [2] http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern()
  4. Dec 1, 2011 #3
    Re: Java [String a = new "test"] vs [String b = "test"]

    Thanks for the detailed answer!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook