aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Q? from Majji Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Q? from Majji" Watch "Q? from Majji" New topic
Author

Q? from Majji

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Nov 22, 2008
Posts: 18944
I am sorry it is printing false.
sachin patel
Ranch Hand

Joined: Nov 28, 2000
Posts: 75
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.
****************************************************


Sachin,<P>****************************************************<BR>Learn from others mistakes. Life is too short to make all yourself.<BR>****************************************************
Anand Yadav
Greenhorn

Joined: Dec 28, 2000
Posts: 5
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


Anand
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Q? from Majji
 
Similar Threads
Doubt on "=="
Q.9 from Majji's paper 1
Majji Mock Q #9
toString
toString()........