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

  • Java
  • Thread starter estro
  • Start date
  • #1
241
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?
 

Answers and Replies

  • #2
Filip Larsen
Gold Member
1,296
222


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()
 
  • #3
241
0


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!
 

Related Threads on Java [String a = new test ] vs [String b = test ]

  • Last Post
Replies
3
Views
6K
Replies
2
Views
1K
Replies
5
Views
1K
  • Last Post
Replies
2
Views
39K
Replies
7
Views
6K
  • Last Post
Replies
7
Views
2K
  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
13
Views
37K
  • Last Post
Replies
10
Views
1K
Top