Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparison

 
ameen ahamed
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Samith Nambiar
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic