2

What is difference between String str = "ABC" and String str = new String("ABC")?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Sachin
  • 184
  • 1
  • 1
  • 7
  • `String str = "abc"; is a String literal,where as String str = new String("abc") is a String Object.` – vhadalgi May 26 '14 at 09:58

1 Answers1

8

String

In Java String is a special object and allows you to create a new String without necessarily doing new String("ABC"). However String s = "ABC" and String s = new String("ABC") is not the same operation.

From the javadoc for new String(String original):

Initializes a newly created String object so that it represents the same sequence of characters as the argument; [...]

Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

In other words doing String s = new String("ABC") creates a new instance of String, while String s = "ABC" reuse, if available, an instance of the String Constant Pool.

String Constant Pool

The String Constant Pool is where the collection of references to String objects are placed.

String s = "prasad" creates a new reference only if there isn't another one available. You can easily see that by using the == operator.

String s = "prasad";
String s2 = "prasad";

System.out.println(s == s2); // true

enter image description here

Image taken from thejavageek.com.


new String("prasad") always create a new reference, in other words s and s2 from the example below will have the same value but won't be the same object.

String s = "prasad";
String s2 = new String("prasad");

System.out.println(s == s2); // false

enter image description here

Image taken from thejavageek.com.

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58