user900721
user900721

Reputation: 1437

Question related to string

I have two statements:

String aStr = new String("ABC");
String bStr = "ABC";

I read in book that in first statement JVM creates two bjects and one reference variable, whereas second statement creates one reference variable and one object.

How is that? When I say new String("ABC") then It's pretty clear that object is created. Now my question is that for "ABC" value to we do create another object?

Please clarify a bit more here.

Thank you

Upvotes: 0

Views: 46

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500575

Using a string literal will only create a single object for the lifetime of the JVM - or possibly the classloader. (I can't remember the exact details, but it's almost never important.)

That means it's hard to say that the second statement in your code sample really "creates" an object - a certain object has to be present, but if you run the same code in a loop 100 times, it won't create any more objects... whereas the first statement would. (It would require that the object referred to by the "ABC" literal is present and create a new instance on each iteration, by virtue of calling the constructor.)

In particular, if you have:

Object x = "ABC";
Object y = "ABC";

then it's guaranteed (by the language specification) than x and y will refer to the same object. This extends to other constant expressions equal to the same string too:

private static final String A = "a";

Object z = A + "BC"; // x, y and z are still the same reference...

The only time I ever use the String(String) constructor is if I've got a string which may well be backed by a rather larger character array which I don't otherwise need:

String x = readSomeVeryLargeString();
String y = x.substring(5, 10);
String z = new String(y); // Copies the contents

Now if the strings that y and x refer to are eligible for collection but the string that z refers to isn't (e.g. it's passed on to other methods etc) then we don't end up holding all of the original long string in memory, which we would otherwise.

Upvotes: 2

Thilo
Thilo

Reputation: 262514

You will end up with two Strings.

1) the literal "ABC", used to construct aStr and assigned to bStr. The compiler makes sure that this is the same single instance.

2) a newly constructed String aStr (because you forced it to be new'ed, which is really pretty much non-sensical)

Upvotes: 2

Related Questions