• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloaded toString() of wrapper class doubt

 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K&B Chapter3 page 242

All of the numeric wrapper classes provide an overloaded, statictoString() method that takes a primitive numeric of the appropriate type (Double.toString() takes a double, Long.toString() takes a long, and so on) and, of course, returns a String.

Then what is the problem with Short and Byte wrapper classes ? thanks


Output

C:\SCJP\Chapter3\Wrapper_Classes>javac ToStrin
ToString.java:12: cannot find symbol
symbol : method toString(int)
location: class java.lang.Byte
String s2=Byte.toString(1);
^
ToString.java:15: cannot find symbol
symbol : method toString(int)
location: class java.lang.Short
String s3=Short.toString(1);
 
Matthew Brown
Bartender
Posts: 4566
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Byte has a static toString method that takes a byte variable. But you're passing an int, which is why it won't compile. Cast it to a byte first and it will be fine. Similarly for Short.
 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is really tough to identify that where we have to do cast and where compile will take care about it,anyways thanks Matthew.
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
default numerical literals are int by default. so when you did Byte.toString(1) , the value 1 will be treated as an integer. so that means here you are doing narrowing conversion. you are putting big bucket in small bucket which will require explicit conversion, as opposed to widening conversion which happens explicitly. so here you have to do explicit cast.
 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
gurpeet singh wrote:default numerical literals are int by default. so when you did Byte.toString(1) , the value 1 will be treated as an integer. so that means here you are doing narrowing conversion. you are putting big bucket in small bucket which will require explicit conversion, as opposed to widening conversion which happens explicitly. so here you have to do explicit cast.


Yes, i know small and big bucket story but when you do byte b=1; it doesn't need casting, compile will do conversion automatically i.e int value into byte so i thought it should also work here but not so, it creates confusion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic