-1

In Java, is there a difference between the following two pieces of code? I'm looking for answers in terms of memory usage and the String pool.

The first:

String s = new String();

s = "abcdef";

The second:

String s = new String("abcdef");

Thanks.

arshajii
  • 127,459
  • 24
  • 238
  • 287
ConorW
  • 277
  • 1
  • 4
  • 13
  • 2
    in the first case you create two strings (one empty) and second "abc...". In the second just one. – gregory561 Dec 29 '12 at 20:57
  • 2
    http://stackoverflow.com/questions/2486191/java-string-pool?rq=1 among others contain a lot of information regarding this. If there's something from all the various questions and answers on SO that you don't understand, a specific question would be more useful. – Brian Roach Dec 29 '12 at 20:58
  • And the first comment here is completely incorrect. Both cases create two `String` objects. String literals are interned and stored in the string pool. – Brian Roach Dec 29 '12 at 21:48

1 Answers1

2

You do a creation and a value assignment in the first one. In the second one you just do a creation. You make (nearly) twice processor activities in the first one. Speaking of memory, there's no difference.

And String pool explanation to your question:

What is the Java string pool and how is "s" different from new String("s")?

Community
  • 1
  • 1
İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
  • why there is no difference in memory? you create two in fact two string objects in the first case. – gregory561 Dec 29 '12 at 21:02
  • 1
    @gregory561 - and you create two in the second case ;) That literal doesn't magically go away - it goes in the string pool. – Brian Roach Dec 29 '12 at 21:18