Re: Difference between String variable and String Class definition





Tom Fredriksen wrote On 03/30/06 05:02,:
Chris Uppal wrote:
>

Lets assume I have got it right, then the question was why dont they
both compile to the bytecode of the first statement? This was the point
of seemingly similar, as in similar byte code, not syntax.

As I say, they are not similar. The compiler would be in error (/grossly/ in
error!) if it generated the same bytecodes for the two statements.


As you see, the third case:
String c = new String("Java");
is a minor variant on the second:
String b = new String();
not on:
String a = "Java";


I understand how it works now, but I don't understand why. The question
that keeps popping into my head is, does there need to be a difference
between the first example and the third?

I understand the mechanics and requirements from the language of how it
should work when using new etc, but why can't it optimise it to be the
same as example three? I.e why is there a need to have two different
ways of doing the same thing, especially when they operate slightly
different for, to me, no apparent reason?

The fundamental promise of `new' is that it will
create a brand-new object, distinct from all existing
objects. The `new' operator can never "recycle" an
old object, not even if the old object's state ("value")
is the same as the one being created.

It's easy to see why this is crucial for a mutable
class. Two distinct instances of a mutable class could
start life with identical contents, but the program can
change each one independently of the other. If the two
shared the same underlying object instance, this would
not work.

For an immutable class like String this guarantee
of instance uniqueness is less useful. Once the object
is created its contents will remain forever unchanged,
so there's not much point in having multiple copies of
the same unchangeable object lying around. However, the
notion of "immutable" is not quite as cut-and-dried as
the simple word makes it sound (there was a recent thread
on this very topic), and the Java language doesn't have
a means to express all the shadings and gradations of
"immutability." In the interests of simplicity, perhaps,
Java has just one `new' operator rather than a host of
slightly different `newish' operators -- and since `new'
must allow mutable objects to work properly, `new' must
always, always, always generate a brand-new object.

It's been pointed out that the difference is detectable:
in Chris' example, a==c is false because the two variables
refer to distinct String objects. The two happen to have
identical content (so a.equals(c) is true), but are not
the same object. As I wrote earlier, if there are five
pennies in my pocket and five in yours, our pockets have
identical content -- but I will protest if you try to take
the pennies from my pocket, because my pocket is not yours.

--
Eric.Sosman@xxxxxxx

.



Relevant Pages