File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper Classes 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 "Wrapper Classes" Watch "Wrapper Classes" New topic

Wrapper Classes

Vineela Devi
Ranch Hand

Joined: Dec 20, 2003
Posts: 191
Byte b = new Byte(10); //Compile error
But if i do like this its ok
byte b = 10;
Byte by = new Byte(b);
anyone pls explain why the compiler is reporting error in the first case even though the value passed is well within the range of byte and the constructor of Byte class takes byte value as parameter.
Tushar Gorde

Joined: Jan 30, 2004
Posts: 3
Hey Dear..
If u create an object like
Byte b=new Byte("10");
then it wont give any error.... So the first constructor of Byte Wrapper class is of type string parameter.
Iain Ross

Joined: Jan 30, 2004
Posts: 10
Byte b = new Byte(10);
In this case I believe the 10 passed as a parameter is considered to be a literal, as such it is implicitly of type int (32 bit). The wrapper class Byte does not have a constructor that accepts an int and so you get a compiler error.
Karen Liu

Joined: Sep 14, 2003
Posts: 16
byte b = 10; Byte by = new Byte(b);

This is an assignment and compiler does the narrow conversion automatically.
And you what you passed into the constrcutor is axtually the byte type.
Byte b = new Byte(10); //Compile error

10 is an int type and for method paramenters, compiler doesn't do
the automatic narrow conversion.
That's why compiler error
Gian Franco
Ranch Hand

Joined: Dec 16, 2003
Posts: 977
All wrapper class constructors accept two types
of constructor arguments, String and the corresponding
primitive type (e.g. the wrapper type Short accepts
String and short).
Only exception to the rule are the wrapper classes
Character, which accepts only the primitive type
char, and Float which accepts double as well as String
and float.
Gian Franco

"Eppur si muove!"
Sham Grandhe
Ranch Hand

Joined: Dec 16, 2003
Posts: 73
hai friend,
this could help u man,
Byte x = new Byte((byte)10);
I agree. Here's the link:
subject: Wrapper Classes
It's not a secret anymore!