Author Topic:   Probably you all know it already, but still..
maha anna
bartender
posted March 02, 2000 01:46 PM             
Probably you all know it already. I just wanted to say that we should be careful when we see code like the foll.
regds
maha anna
code:

Byte byteVar = new Byte("100");
if(byteVar.toString() == byteVar.toString())
System.out.println("Byte.toString() == YES");
else
System.out.println("Byte.toString() == NO"); //NO is printed


String strVar = new String("maha");
if(strVar.toString() == strVar.toString())
System.out.println("string.toString() == YES"); //YES is printed
else
System.out.println("string.toString() == NO");



[This message has been edited by maha anna (edited March 02, 2000).]

monty
greenhorn
posted March 02, 2000 02:48 PM             
Ok, up stumpt me ...
I ran the code ...
Why is (byteVar.toString() == byteVar.toString()) FALSE
-----

Tony Alicea
sheriff
posted March 02, 2000 03:01 PM             
The first part creates two different String objects when the toString() method is called.

Jim Yingst
sheriff
posted March 02, 2000 05:48 PM             
Maha Anna's second result was the one I found surprising. I guess the thing is that while most of the time toString() creates a whole new String, it's not actually obligated to (not like the new String() constructor is). Within the String class Sun evidently decided it was easier to just return another reference to the current instance, since it already is a string. As demonstrated here:

code:
    String strVar = new String("maha");
System.out.println(strVar.toString() == strVar); // prints true

Thanks for pointing that out, Maha. (Is that an appropriate nickname?)

Rolf Weasel
ranch hand
posted March 02, 2000 07:16 PM             
Jim, I think i read that this also happens with String.toUpperCase(). If the string is already Uppercase only, the original reference is returned and no new string object is created.

Tony Alicea
sheriff
posted March 02, 2000 09:16 PM             
And with String.trim() also...

maha anna
bartender
posted March 02, 2000 09:38 PM             
I have tested the foll. methods of String class. For simplicity (and laziness also ) I have omitted the args for these methods. All these return the same String object ref( upon which the method is invoked )when the returned String's content is same as the original.(case sensitive)
touppercase(),tolowercase(),toString(),substring(),concat(),trim(),valueOf(),replace()
Jim, All call me Maha ,kind of pet name..
regds
Maha anna

[This message has been edited by maha anna (edited March 02, 2000).]

|