0

For Example..

String herName = new String("clark");

and

String hisName = "michal";

1) The first piece of code exactly does, it will create new string object in the heap memory with reference .

2) The second line of code , its an string literal which create string object in string constant pool, not in actually heap memory.

Then what's the benefit, ?

trincot
  • 317,000
  • 35
  • 244
  • 286
Z.I.J
  • 1,157
  • 16
  • 36
  • http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly – pvg Nov 26 '15 at 05:33

2 Answers2

0

The benefit is that new String(String s) is a copy constructor for Strings and works as intended, providing a copy of a given String.

Calling new String("literally") is not some special feature designed for literals. In fact, the inverse situation would be most unusual, what good would it be if new String(String s) did not work as intended when a literal was used?

Finally, the notion that new object is completely on the heap may be misleading, you do have a new object but because String is immutable it is safely backed by the same char[] value, even in the Java 8 source the reference is merely passed on:

public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}
Linus
  • 894
  • 7
  • 13
-2

The second case is susceptible to something called interning - if another string is initialized to that same value, the same object will be used for that.

Ambidextrous
  • 810
  • 6
  • 14