String

I always used to think that the following two meant the same :-

String a="abc";

and

String a =new String ("abc");

but today when I did a javap on both of these statements here is what I got, in respective order

publicstaticvoid main(java.lang.String[]);

Code:

0:ldc#2;//String abc

2:astore_1

3:return

and for new operator

Code:

0:new#2;//class String

3:dup

4:ldc#3;//String abc

6:invokespecial#4;//Method java/lang/String."<init>":(Ljava/lang/String;)V

9:astore_1

10:return

The code was simply

publicstaticvoid main(String[] args){

String a=new String("abc");

}

[1336 byte] By [kilyasa] at [2007-11-26 21:28:26]
# 1

The first one refers to a String object that's in the constant pool. All occurences of that line will refer to the same object.

The second one creates a new String object that's a copy of the one in the constant pool. Multiple occurences of this line will create multiple String objects.

The only reason I know of to ever use new String() is when you use substring or a similar operation that can create a new String object backed by the same array. largeString.substring(a small range) can leave a large char[] around just for the few characters you care about in the substring. new String will give you a new char[], properly sized.

jverda at 2007-7-10 3:08:58 > top of Java-index,Java Essentials,Java Programming...
# 2
Well, string pool and all that, right?
DrLaszloJamfa at 2007-7-10 3:08:58 > top of Java-index,Java Essentials,Java Programming...