File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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


ameen ahamed

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");
why this fragment prints false ?
Sharada Kumaran

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,
returns true.
Please correct me if my understanding is wrong.

Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
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
harder u try luckier u get
I agree. Here's the link:
subject: comparison
It's not a secret anymore!