| Author |
casting/autoboxing make simple?
|
Peter Hsu
Ranch Hand
Joined: Aug 25, 2006
Posts: 71
|
|
Hi
Can someone give me a few rules of when casting/autoboxing can happen and when couldn't it?
I am confused
for example, am I right here?
Integer i = ....;
i.equals(j);
could only take int or Integer
but
i==j
would work whenever either i or j is primitive and the other one can be any type of wrapper (Byte/Integer/Short/Long/Float/Double)
when you are using >, <, >=, <=
you are forcing the compiler to autobox, so any type of comparison would work
when initializing
byte/short/int x = (some integer) will always work as long as the value does not overflow
double x = (some number) will always work
long/float value always have to be followed with a l or f respectively
Short/Byte x = new Short/Byte( /*some integer*/ ) - parameter has to be cast to short/byte
Integer/Float/Double x = new Integer/Float/Double( /*some number*/ ) - do not require casting, just type in the number and it would work
please check this out as this is what I understood
does it serve as a decent overview for this confusing topic?
am I missing something or mistaken in anything?
|
 |
Prince Chauda
Greenhorn
Joined: Feb 13, 2008
Posts: 8
|
|
Peter Hsu wrote:Hi
Can someone give me a few rules of when casting/autoboxing can happen and when couldn't it?
I am confused.........
In java , in case of primitives any smaller data type can be assigned to greater one .This is called widening.
But for narrowing you have to make a cast if the assigned value is greater than its size limit.
For rest of the things refer "Kaithy Sierra" for SCJP.
|
 |
Peter Hsu
Ranch Hand
Joined: Aug 25, 2006
Posts: 71
|
|
Prince Chauda wrote:
In java , in case of primitives any smaller data type can be assigned to greater one .This is called widening.
But for narrowing you have to make a cast if the assigned value is greater than its size limit.
For rest of the things refer "Kaithy Sierra" for SCJP.
Yeah I can imagine this is the basic idea
However, things seems a little counter-intuitive as you go further
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
|
|
|
This is where it becomes complicated: the official list is in the Java Language Specification.
|
 |
 |
|
|
subject: casting/autoboxing make simple?
|
|
|