aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is this output ?? 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 "Why is this output ??" Watch "Why is this output ??" New topic
Author

Why is this output ??

Vishy Karl
Ranch Hand

Joined: Sep 08, 2003
Posts: 116
Hi All,
Given the foll. code in a mock exam.
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");
A) Compilation error, toString() is not avialable for Byte.
B) Prints "True".
C) Prints "False".
Can anyone tell me why is the output False and not True ??
I thought it should be B but it is C
Plz. Explain.
Thanks,


"The man who can drive himself further once the effort gets painful is the man who will win." <br />Roger Bannister
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Hi Vishy,
I guess this should be the reason. The API for the toString() in Byte class says
=============================
toString
public static String toString(byte b)
Returns a new String object representing the specified Byte. The radix is assumed to be 10.
Parameters:
b - the byte to be converted
Returns:
the string representation of the specified byte
===========================
Note "Returns a new String object...".
Try this code to check for values.
class a
{
public static void main(String args[])
{
Byte b = new Byte("127");
if(b.toString().equals(b.toString()))
System.out.println("true");
else
System.out.println("false");

}
}


Thanks,<br />Lakshmi.
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Here is the version of toString which you want.
I posted the one with a byte argument.Sorry...
==========================
toString
public String toString()
Returns a String object representing this Byte's value.
===================
Vishy Karl
Ranch Hand

Joined: Sep 08, 2003
Posts: 116
Thanks a lot Lakshmi,
It helped )
Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
hello Vishy, each time you call the toString() method a new string (new object) is created and returned. To check their equality you need to use the equals() method as Lakshmi suggested.
The code you posted will compare the reference of the two objects which are definitly different therfore explains the result you had.
Hope this helps.


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. - What truth? - That there is no spoon!!!
 
Consider Paul's rocket mass heater.
 
subject: Why is this output ??