File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting" Watch "casting" New topic


Ramm Kummar

Joined: Feb 10, 2009
Posts: 26
"byte b = 27;
but only because the compiler automatically narrows the literal value to a byte. In
other words, the compiler puts in the cast. The preceding code is identical to the
byte b = (byte) 27; // Explicitly cast the int literal to a byte"


1)but if this is tried, compiler not doing implicit casting. Whats the reason for this?

byte = 7000;
it should be byte =(byte) 7000;

2) Casting is used among objects which are related to each other in the inheritance tree otherwise compiler error(inconvertable types) will be thrown. How these primitives are related? since their wrapper classes are not in same inheritance tree. They are not related to each other. How is this casting possible among primitives?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38064
In the case of byte b = 7000; a cast is necessary because the compiler can "see" that the literal is out of range for a byte.

In the case of class-casting, that is completely different from primitive casting, and the only similarity is the name.
I agree. Here's the link:
subject: casting
Similar Threads
under what conditions can an int be assigned to a byte?
Operators Question
Type Conversion doubt
casting objects