[NTLUG:Discuss] Java/Linux versus school teacher.
Patrick R. Michaud
pmichaud at pobox.com
Mon Mar 19 10:57:16 CDT 2007
steve wrote:
> Do we have any Java/Linux guru's in the house?
> [...]
> Assume x and y are String variables with x="Hello" and y=null.
> [...]
> 2) It the operation y="Hello"; is performed then the result
> of (x==y) is:
> a) true
> b) false
> c) x and y becoming aliases
> d) x being set to the value null
> e) a run-time error
>
> Question 2 is a problem. My son said "(a) true" but the
> teacher says that the answer is "(b)false" - and whilst
> I'm not a Java expert (I'm a C++ person) I can see why.
Actually, the answer in this case is "(a) true". IIRC,
Strings in Java are immutable, and so the compiler optimizes
the compiled code such that any repeated constants are
folded to always refer to the same String object. Thus, with
> String x="Hello";
> String y="Hello";
The compiler generally optimizes this so that x and y both
refer to the same String object. Thus with
> if ( x==y )
> println ( "true" ) ;
> else
> println ( "false" ) ;
the answer comes out "true". :-)
A useful test might be to try something like:
String x = "Hello";
String y = "He" + "llo";
Here, the value of y ends up being the concatenation
of two Strings, which is not likely to be the same object
as x (unless Java is checking for reused String values at
runtime). In this case, the expression "x==y" should
return false.
Also, be sure to test _exactly_ what the question asks,
which is an assignment to y (y="Hello") as opposed to
an initialization (String y="Hello").
String x = "Hello";
String y = "";
y = "Hello";
if (x == y)
...
At any rate, I think that your son has a case to be
made here. I'm sure that the teacher was intending to
test the knowledge that in Java one cannot rely on the
== to test two Strings for equal values, but that's not
what the question is actually testing. In Java, when
x and y are Objects the expression x==y means "are 'x'
and 'y' the same object", and with Strings the compiler
is free to re-use existing String objects that result
in the same value.
So, the answer "(a) true" is equally as wrong as "(b) false",
in that it's completely wrong to assume that x==y will
give a repeatable answer based on the values of x and y
(because x==y doesn't check for value equality).
The answer I would've given is
(f) None of the above. The expression x==y tests
whether x and y refer to a common String, not
that two Strings have identicial values. In order
to test for identical values, one uses x.equals(y) .
Pm
More information about the Discuss
mailing list