-2

In Java 5.0 , what is the difference between the following?

1.

String variable = "hey";

2.

String variable = new String("hey");
logoff
  • 3,347
  • 5
  • 41
  • 58

2 Answers2

1

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

Community
  • 1
  • 1
ed_me
  • 3,338
  • 2
  • 24
  • 34
0

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
Coding Enthusiast
  • 3,865
  • 1
  • 27
  • 50