>>>>> "Jacob" == Jacob Nikom <[EMAIL PROTECTED]> writes:
> Hi,
> This is not really Java-Linux, but more like Java question.
> May be it is different for Java Linux implementation, that is
> why I decided to ask.
Actually, the language specification is pretty specific in this area -
see JLS (2nd Ed) sections 3.10.5 and 15.9...
> My friend and I recently tried to figure out which String
> implementation is more efficient and correct:
> String a = "bbbbbb"
> or
> String a = new String("bbbbbb");
> He said that the second one is a copy constructor which is less
> efficient. It uses more memory and requires to copy the array
> from one place to another. I said that they are the same and it is
> simply different syntax. Who is right?
Your friend is half right:
The former case assigns a to the (interned) string literal "bbbbbb".
The latter case assigns a to a new instance of String with the same
sequence of characters as the (interned) string literal "bbbbbb".
Now, the reason that he is only half right is that String instances
may share the internal char arrays - this is why Strings are
immutable, after all. So, in the first case, there is one String
object instance which refers to one char array. In the latter case,
there are two String instances, both referencing the same char
array.
I believe that (current) java sematics would forbid these being
equivalent, as the second case would seem to *require* allocation of
new space (e.g. the new object), whereas the first may not. In
particular, java semantics requires the following behavior:
String a = "bbbbbb";
String b = "bbbbbb";
String c = new String(a);
String d = new String(b);
String e = d.intern();
(a==b) // required to be true!
(a!=c) // required to be true.
(c!=d) // required to be true.
(a==e) // required to be true.
and, of course, they are all .equals().
See JLS (2nd ed), pp 27.
cheers,
-mik
--
Michael Thome ([EMAIL PROTECTED])
----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]