wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "comparison" Watch "comparison" New topic
Author

comparison

ameen ahamed
Greenhorn

Joined: Jan 02, 2001
Posts: 25
class test
{
public static void main(String args[]){
Byte b1=new Byte("127");
if(b1.toString()==b1.toString()) System.out.println("True");
else
System.out.println("False");
}
};
why this fragment prints false ?
Sharada Kumaran
Greenhorn

Joined: May 23, 2001
Posts: 29
My guess is that b1.toString() and b2.toString() return two different String objects.
Khaled says " Each wrapper class overrides the toString() method. The overriding method returns a String object representing the primitive value. "
In this case, b1.toString() and b2.toString(), maybe returning two objects, each occupying a different memory location, but having the same value.
The operator == is comparing for object equality, and not value equality. On the other hand,
b1.toString().equals(b2.toString())
returns true.
Please correct me if my understanding is wrong.


Sharon
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
hi
it returns false because like sharada said returns two new String objects and since == checks the refernces this returns false
also note that if the same code was replaced with Boolean or String objects instead of Byte or any other wrapper classes then the value printed would be false .... this is because in both these cases the Strings are maintained in the Constants pool and share the same String object ... hence would return TRUE
hope that helps
Samith.P.Nambiar
-----------------------------
harder u try luckier u get
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: comparison
 
Similar Threads
Interesting Question
* Byte == comparision
byteRef.toString() == byteRef.toString() ?
toString( ) method
Why is " == " on different strings with same content is returning "false"