hello, i came accross the following code: Byte b1 = new Byte("123"); if (b1.toString() == b1.toString()) System.out.println("true"); else System.out.println("false"); } could you tell me why it prints "false"?
Hello, The .toString() method will return a different string object each time it is run, and the '==' will check to see if these "objects" are equal. They are not, so your code returns false. If you want to check if strings are equal you need to use the .equals() method, such as;
The above code will give you a "true" condition. Hope this helps, Pat B.
posted 17 years ago
Hello Pat, Yes, it does help. I guess i just have to remember that for any Object except one of type String, the following code will always return false. Object object = new Object(); if (object.toString() == object.toString()) System.out.println("True"); else System.out.println("False");
posted 17 years ago
Actually, using '==' on any object, including strings, will usually return false, unless the references have been set equal to each other by using '='. Here's a poorly written code example that may help...
The first if will evaluate to false, printing the not equal message. The second will evaluate to true because the contents are being compared. The third will evaluate to true as well because the references were set equal to each other. HTH again... Pat B.
[This message has been edited by Pat Barrett (edited February 06, 2001).]
Hi, just addition to knowledge pool: String AND Boolean are overriden to compare content, other classes like StringBuffere, Byte etc are not, and they are doing "shallow comparasion" - compare references, not content. So, only String and Boolean!
Hi Branka, Actually, the Byte class does override the Object.equals() method to compare the values of the objects. The API is not very clear on this however the source code shows the following:
The other wrapper classes: Integer, Boolean, Character, Float, etc also override equals() to compare the actual value of the objects. There's a tendency to think that because String.equals() compares the String values, StringBuffer does the same however StringBuffer does not override Object.equals() and only checks if the two object references are the same. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform
Originally posted by Ana Inna: hello, i came accross the following code: Byte b1 = new Byte("123"); if (b1.toString() == b1.toString()) System.out.println("true"); else System.out.println("false"); } could you tell me why it prints "false"?
This is because the == operator checks whether both strings are in the same memory pool .If u try it with the equals method it will return true i.e if (b1.toString().equals(b1.toString()))