• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this output ??

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");

}
}
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Lakshmi,
It helped )
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic