1

I've worked a lot of refactoring on my old code and I noticed that I have created strings in two ways:

First way - using a new operator:

String stringA = new String ("String A");

Second way - using literal:

String stringB = "String B";

Could anyone explain which of these way is better and why?

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • 2
    This is one of the cases where the simplest, cleanest, most readable code is also the best performance code. Certainly use the second way in all new code. – Patricia Shanahan Nov 24 '13 at 19:16

1 Answers1

7

In short: A better way is second statement.

Explanation:
String is immutable in Java. Regarding the fact that object can always be reused if it is immutable, you should always avoid first statement because this statement needlessly creates a new String instance always when it is executed.

Instead of this you should always use second statement because it uses a single String instance and it is guaranteed that the object will be reused.

I highly recommend the book: Effective Java, Second Edition by Joshua Bloch. More info for your question and some benchmark results you can find here - Effective Java - Same method invocation time despite creating multiple instances.

I hope that facts are helpfull.

Community
  • 1
  • 1
Bosko Mijin
  • 3,287
  • 3
  • 32
  • 45
  • Thanks Bosko for clear explanation and useful links. That help me a lot. –  Nov 24 '13 at 19:28