Win a copy of Microservices in Action this week in the Web Services forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Q? from Majji  RSS feed

 
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.
 
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.
****************************************************
 
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!