Java String Identity (was Re: [thelist] PHP question... checking string length)

Matt Warden mwarden at gmail.com
Mon Mar 28 11:17:41 CST 2005


Andrew,

On Mon, 28 Mar 2005 19:52:40 +0900, Andrew Clover <and-evolt at doxdesk.com> wrote:
> (It is indeed unusual for an immutable value type one can write as a
> literal to have identity, which is why Java Strings trip people up.)

I wasn't sure what you were referring to when you mentioned identity,
so I googled it and found this:

http://www.witscale.com/scjp_studynotes/code_examples/chapter3/string_equality.html

This is actually something I did not know. I just wanted to clarify
that one of my examples in my previous post is technically not correct
(although it is only due to me trying to simplify the example, as I
don't know why anyone would ever create two variables with the same
literal string, unless they *wanted* them *not* to reference the same
location in memory).

I gave this example:

String a = "a";
String b = "a";
Strinc c = a;

boolean thisisfalse = (a == b); // because a and b are not pointing to
same object
boolean thisistrue = a.equals(b); // because "a".equals("a")
boolean thisistrue = (a == c);  // because a and c are pointing to the
same object
boolean thisistrue = a.equals(c); // because "a".equals("a")

The first test is actually wrong, because as the article suggests,
literals that exist already in the memory pool are re-used and
variables a and b would indeed reference the same memory location. All
of the above would be return true.

But, like I said, this is a symptom of the example, as why would
anyone create two literal strings and then test to see if they are
equal? The point is that == tests references and not values of strings
in Java. So, "in the real world" when one is testing strings, one is
usually testing input of some type (file i/o, user input, etc.) to see
if it is or is not a certain value. In this case, the 'identity
gotcha' doesn't apply and the point of my original example would
apply.

Thanks for pointing this out, Andrew. If this is what you were
referring to regarding the dumb design decision, I'd have to give you
a hearty 'amen'.



-- 
Matt Warden
Miami University
Oxford, OH, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.


More information about the thelist mailing list