[NTLUG:Discuss] Java/Linux versus school teacher.

steve sjbaker1 at airmail.net
Mon Mar 19 12:37:38 CDT 2007


Chris Cox wrote:

> However, with that said, I don't think there's anything in
> Java that says two strings CAN'T equate using "==" to being
> true... but you just have to understand they can be DIFFERENT
> objects and therefore, you shouldn't ASSUME that using "=="
> would produce a true value.  It's the teacher's assumption
> that "==" means a string content comparison... this is
> the information MISSING from the question.

No - quite the opposite.  The teacher said (somewhat
correctly in my opinion) that the result would be FALSE.

And the very reason for asking that question is clearly
to probe whether the kids understand that '==' does not
do a string compare.

The trouble is (or so it seems) that something in (at least)
the Linux Java is resulting in a 'true' result even though
it's not doing a string compare.

Of course my kid got the answer 'true' for 100% the wrong
reason - he DID assume it would do a string compare - but
then wondered why they'd been teaching him to use the
compare method inside the String class...so he deserved
not to score a point on this question - but it's disturbing
that the 'official' answer was also wrong.

> Of course, in OO languages that support operator overloading,
> the question becomes even more complex (be glad it was java
> and not C++ or C#).

Yeah - that was my concern.  I knew that Java's '==' compared
addresses (in C++ terms) and not string content - but since
'String' is not a primitive type, it's perfectly possible
that 'operator==' was overloaded (again in C++ terms) to do a
string compare.

So as a non-Java person myself, I didn't know how to answer the
question without reference to the String class documentation.

But the question is quite hard to answer even in C++:

   const char *x = "Hello" ;
   const char *y = "Hello" ;
   if ( x==y )
     printf ( "true" ) ;
   else
     printf ( "false" ) ;

...you don't truly know the answer to this question because
(at least in g++) you can compile with '-fwritable-strings'
and ensure with 100% certainty that the test would always return
false or leave it at the default and not know for sure but
syspect that the compiler would smoosh the two copies of the
"Hello" string into a single storage location.

But perhaps Java is 'officially' specified such that those two
'Hello' strings MUST be different objects - which would imply
a bug in the Linux version.   The key question here is whether
I can continue to rely on the Linux Java implementation to
produce 'correct' results for my kid's education.




More information about the Discuss mailing list