[NTLUG:Discuss] Java/Linux versus school teacher.
Patrick R. Michaud
pmichaud at pobox.com
Mon Mar 19 11:34:32 CDT 2007
On Mon, Mar 19, 2007 at 10:57:16AM -0500, Patrick R. Michaud wrote:
> steve wrote:
> > [...]
> > 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.
It might also be worth noting that many C compilers also
re-use string constants in a similar manner:
$ cat t.c
#include <stdio.h>
int main(int argc, char* argv[])
{
char *x = "Hello";
char *y = NULL;
y = "Hello";
if (x == y)
printf("x == y\n");
else
printf("x != y\n");
return 0;
}
$ gcc -o t t.c; ./t
x == y
$
Obviously the expression x == y isn't doing a string comparison,
it's just checking that x and y point to the same location in
memory. But the compiler creates just one instance of the
"Hello" string constant to be used in both places where it
occurs in the program.
Pm
More information about the Discuss
mailing list