wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes primitive conversion 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 "primitive conversion" Watch "primitive conversion" New topic

primitive conversion


Joined: May 15, 2000
Posts: 16

1) byte b=123 //this works 123 is an int but you do not need a cast for it to be converted to a byte since 123 is in the range of -127 to 128.
2) Byte b = Byte(123);//would generate a compile error explicit cast needed to convert int to byte.But this worked fine in 1).
In RHE it said that the rules for conversion in Assignment is the same in Method Call why wont no.2 work?
jyoti Agrawal

Joined: Nov 26, 2002
Posts: 3

The constructor for the Byte takes only byte as an argument or string as the argument.
in your question u have said Byte(123)
123 is an int which cannot be downcasted to byte or be converted to string.Hence it is giving u the error.
i hope your doubt is cleared now.
Suma Narayan
Ranch Hand

Joined: Apr 03, 2000
Posts: 136
Hi joy,
Jyothi, has already told you the reason for the error you are getting. I am just adding few details.
There are two ways to construct a wrapper class object.
1. By passing the value to be wrapped into the appropriate constructor. For e.g
boolean bool = true;
Boolean bn = new Boolean(bool);

so the constructor is of the form,
Boolean bn = new Boolean(boolean bool);
In the example mentioned by you, it should be constructed in
the following way.
byte b = 123;
Byte bt = new Byte(b);
2. You can pass into the constructor a string that represents the value to be wrapped. The only exception to this way of constructing is the wrapper class Character.
So you can also say,
Byte bt = new Byte("123");
There is always a possibility that a string will not represent a valid value. In such cases, exception "NumberFormatException" is thrown. Only Boolean does not throw this exception.
I hope the above explanation clears your doubt.
[This message has been edited by Suma Narayan (edited May 23, 2000).]
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
I just want to add on what has been said already. Specifically I want to correct you on this statement and I quote :
1) byte b=123 //this works 123 is an int but you do not need a cast for it to be converted to a byte since 123 is in the range of -127 to 128.
123 is not an int in the snipet above. If it were explicitly defined as an int prior to the assignment, that assignment would not succeed and would raise a Compiler error, even though 123 can fit in a byte. Here is works OK because 123 is used as a literal whose size fits in a byte.
I agree. Here's the link: http://aspose.com/file-tools
subject: primitive conversion
jQuery in Action, 3rd edition