permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Byte to string 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 "Byte to string " Watch "Byte to string " New topic

Byte to string

preeti dengri
Ranch Hand

Joined: Nov 30, 2000
Posts: 111
majji exam 1 qno 9
Byte b1 = new Byte("127");
3: if(b1.toString() == b1.toString())
4: System.out.println("True");
5: else
6: System.out.println("False");
what will be the output???
Stevie Kaligis
Ranch Hand

Joined: Feb 04, 2001
Posts: 400
Fazal Ahmad

Joined: Mar 06, 2001
Posts: 18
Hi Preeti:
The output would be 'False'. The reasoning behind is that the b1.toString() would return a String object each time and we all know that if we use '==' on 2 String objects they would not be equal (until and unless they were constructed using the same literal, however thats not the case here)
Hope the above helps.

Vegad Arvind
Ranch Hand

Joined: Jan 10, 2001
Posts: 42
Hi Fazal,
Byte b1 = new Byte("127"); //line
if(b1.toString() == b1.toString())

in place of line 1 if u change
String b1 = new String("Java");
it will print True. Why ? diff behavior betn Byte(Wrapper class) and String.
i think in String : b1.toString() return same obj ref.

Fazal Ahmad

Joined: Mar 06, 2001
Posts: 18
Hi Arvind:
Quite true; if you call the toString() on a String object, it would return itself i.e. a String object.
However, if you call the toString() on a Byte object, it would return a new String object representing the Byte object's value.
I agree. Here's the link:
subject: Byte to string
It's not a secret anymore!