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

  • Context: Java 
  • Thread starter Thread starter estro
  • Start date Start date
  • Tags Tags
    Java Test
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
estro
Messages
239
Reaction score
0
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?
 
Physics news on Phys.org


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:
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:
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()
 


Filip Larsen said:
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:
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:
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()


Thanks for the detailed answer!