In Java 5.0 , what is the difference between the following?
1.
String variable = "hey";
2.
String variable = new String("hey");
In Java 5.0 , what is the difference between the following?
1.
String variable = "hey";
2.
String variable = new String("hey");
This is a very commonly asked question on stack overflow, this has been marked as duplicate so this answer can probably serve as a reference to the answers; many of which have quite high upvotes: -
new String() vs literal string performance
Difference between string object and string literal
What is the difference between "text" and new String("text")?
Anyhow, my 2 cents, when assigning a literal, you create a reference to an interned string whereas if you use, new String("...")
, you are returning an object reference to a copy of that string.
Have a read of http://en.wikipedia.org/wiki/String_interning
The first one just creates a reference to the object. The second creates a brand new object. The difference will come to your attendtion when you will use the ==
to compare the two objects.
For example:
String variable1 = "hey";
String variable = "hey";
String variable2 = new String("hey");
When Comparing:
variable == variable1 //true
variable1 == variable2 //false