Tom Fredriksen wrote On 03/29/06 18:05,:
Are you saying that the first example does not produce a String object
with the data "java" as its content? I would think it does, doesn't it?
Up to this point, I think I understand your question and
can answer it. The whole process goes something like this:
The compiler sees the literal "java" in the source code, and
generates a corresponding string constant in the class file.
When the class gets loaded, the JVM takes that string constant
and makes a String object out of it. The JVM also arranges
to make just one String object per unique string constant
value, so if you write "java" several times (perhaps in several
different .java files), the JVM folds them all together into
just one String object with the value "java". When the code
is executed (well, the code as given won't even compile, but
let's imagine that we've fixed it), it sets the value of a
reference variable to point to this String object.
All this verbiage is in response to the word "produce,"
because it seems you're puzzled by where things come from.
The important points: All identical literals get turned into
a single String object by the JVM, and an assignment like
`refvar = "java"' causes the reference variable to refer
to that String object. You don't get a new String each time
the assignment is executed; you just keep recyling the old one.
So basically that means that the second example just creates an
additional object which it uses to set up the first object. I would have
thought its was syntactic sugar, nothing more. How one can be fooled.
This part baffles me; I don't know what you mean.
But a question then is why the need for two seemingly similar
statements, but which has different effects.
Maybe similarity is in the eye of the beholder, but the
two don't look very similar to me. One of them uses the
`new' operator and passes an argument to a constructor, the
other does not. `x = y' and `x = new X(y)' look different
to me, and I'm not surprised they do different things.
I do conceive there is a
reason, but is there a real need? generally I see many such things as
just an attempt to be clever than a real need, I could be wrong though.
"Is there a real need" ... for what? There's certainly
a need for the `new' operator, if that's the question. I
suppose you could design an O-O language without constructors
by using only factory methods, but I think it would be pretty
clumsy, so perhaps constructors count as "needed," too.
The String(String) "copy constructor" doesn't seem to be
very useful. It may have some use as a space optimization
when extracting short substrings from long containing strings
whose remains will be discarded, and it may have use in some
esoteric circumstances where you are using String values as
"tokens" that will never be == to each other even if their
contents are identical. Maybe its principal use is as the
basis of "Gotcha!" questions in Java exams ...