[NTLUG:Discuss] Java/Linux versus school teacher.
steve
sjbaker1 at airmail.net
Mon Mar 19 12:46:39 CDT 2007
Patrick R. Michaud wrote:
> 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.
OK - that's what I suspected - and it is indeed what happens
when you run it under Linux (compiling with 'javac' and running
with 'java' from the command line). But if it's like C++, that
optimisation cannot be relied upon - so you actually have no
idea whether the answer is true or false...it's implementation
dependent.
> 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.
It does.
> 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.
Yep.
> 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) .
Tricky to do 'write in' answers on one of those online
multiple choice things! You have 5 radio buttons...click
one!
More information about the Discuss
mailing list