♂To Live Is To Fight™ !♀
      $ = №1 * ♀ = №2

Thứ Bảy, 23 tháng 10, 2010

What is the difference between String a="a" and String a=new("a") ?

I'm assuming you mean "what's the difference between
String a = "a";
and
String a = new String("a");

The simple answer is that in the 2nd case an extra,
unnecessary String object is created. The reason for that is
that even string literals in Java are instances of class
String, so what happens in the 2nd case is that a string
literal "a" is created and then another String object with
a copy of the same value is created.

The complicated answer is that there is another difference.
All Java string literals are saved by the compiler directly
into the class file, the JVM then reads the class file
and creates instances of class String for all the string
literals in the class file. All these instances are saved in
a special internal pool of Strings inside the String class.
What does this mean? It means that if you do:

String a = "a";
String b = "a";

Then both a and b will reference the SAME object (so a==b is
true). But if you do this:

String a = "a";
String b = new String("a");

Then a and b will reference different String objects (both
strings will have the same value, but they will be 2 strings,
not one like in the first case).

You can add a String into the internal pool by invoking the
intern() method on a String. That method creates a new string
with the same value (if none exists in the pool already),
adds it to the pool and returns it.