Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting/autoboxing make simple?

 
Peter Hsu
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is where it becomes complicated: the official list is in the Java Language Specification.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic