Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Classes

 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Iain
 
Karen Liu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
Greetings,
Gian Franco
 
Sham Grandhe
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai friend,
this could help u man,
Byte x = new Byte((byte)10);
regards
shyam
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic