2

Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?

What's the difference between these two statements:

String a1 = new String("abc");

and

String a2 = "abc";

If you could illustrate the difference, that would be great.

Community
  • 1
  • 1
Prostak
  • 3,565
  • 7
  • 35
  • 46

1 Answers1

3

The first one is creating a new String object; the second one is effectively using one which already exists (it's created while loading the class file.) There is virtually never a reason to use the String(String) constructor.

(I say virtually because there is one case: if you're breaking up a huge String by calling substring() and then discarding the original, you can save memory by using this constructor to create new Strings from the sub-strings. That's really an obscure case, though.)

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186