• Post Reply Bookmark Topic Watch Topic
  • New Topic

Q? from Majji  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Can anybody explain the following question?
The following code will give
1: Byte b1 = new Byte("127");
2:
3: if(b1.toString() == b1.toString())
4: System.out.println("True");
5: else
6: System.out.println("False");
This is printing true. Can this toString method be called on any type of object, since in this case it is called on the object of type Byte??
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry it is printing false.
 
sachin patel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi toString method can be called on any class as it is defined in Object class. so every class inherits it, or overrides it.....
And as toString returns a new String object == cannot be used to compare them.... == will always return false as both the string refrences refers to different String Objects...
hope this helps
------------------
Sachin,
****************************************************
Learn from others mistakes. Life is too short to make all yourself.
****************************************************
 
Anand Yadav
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Subborao
try the following code .. by using .equals if seperate object instances of the same class has to compared we compare it with .equals.
class ranch{
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");
}
}
This will return true ..


------------------
Anand
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!