Tutorial by Examples

The boolean type cannot be cast to/from any other primitive type. A char can be cast to/from any numeric type by using the code-point mappings specified by Unicode. A char is represented in memory as an unsigned 16-bit integer value (2 bytes), so casting to byte (1 byte) will drop 8 of those bits (...
Numeric primitives can be cast in two ways. Implicit casting happens when the source type has smaller range than the target type. //Implicit casting byte byteVar = 42; short shortVar = byteVar; int intVar = shortVar; long longVar = intvar; float floatVar = longVar; double doubleVar = floatVar...
As with primitives, objects can be cast both explicitly and implicitly. Implicit casting happens when the source type extends or implements the target type (casting to a superclass or interface). Explicit casting has to be done when the source type is extended or implemented by the target type (ca...
static void testNumericPromotion() { char char1 = 1, char2 = 2; short short1 = 1, short2 = 2; int int1 = 1, int2 = 2; float float1 = 1.0f, float2 = 2.0f; // char1 = char1 + char2; // Error: Cannot convert from int to char; // short1 = short1 + short2; // Err...
Java provides the instanceof operator to test if an object is of a certain type, or a subclass of that type. The program can then choose to cast or not cast that object accordingly. Object obj = Calendar.getInstance(); long time = 0; if(obj instanceof Calendar) { time = ((Calendar)obj).ge...

Page 1 of 1