Using intern in java Strings -
i trying understand java's string
class having hard time understanding situation described below.
consider following example snippet:
string x = new string("hey"); string y = "hey";
if use bool = y == x.intern();
variable bool
equal true
.
my question is:
when make declaration this:
string b = "h"; string = b.intern + "ey"; boolean x = == "hey";
x
's value false
when make a = (b + "ey").intern();
x
's value true
.
why won't x = true
in second example? because declarations in first example not alike? if yes differences?
with first example:
string y = "hey";
java automatically interns string literals such (jls section 3.10.5):
moreover, string literal refers same instance of class string. because string literals - or, more generally, strings values of constant expressions (§15.28) - "interned" share unique instances, using method string.intern.
so when call x.intern()
, interned copy of "hey"
, same object , ==
returns true
.
but in second example, b.intern()
method call evaluated @ runtime, , java's concatenation operator return new string
(not interned), different object string literal "hey"
(interned already), ==
returns false
(different objects).
edit
to clear happens string concatenation, turn jls section 15.18.1:
the result of string concatenation reference string object concatenation of 2 operand strings. characters of left-hand operand precede characters of right-hand operand in newly created string.
the string object newly created (§12.5) unless expression compile-time constant expression (§15.28).
but, b.intern() + "ey";
not compile-time constant expression, resultant string
object has not been interned, , ==
detect it's different object interned "hey"
.
Comments
Post a Comment