Among Java's primitive types, casting between integral types is implicit if widening from a narrow to a wide type like byte to int. Casting in the opposite direction requires an explicit cast which can lose data. Similarly, floating-point types can be implicitly widened but not narrowed without an explicit cast. Char can be implicitly cast to other primitive types but boolean cannot be cast at all.
1. Among integral types, casting is implicit if from
narrow to wide:
byte b; short s; int i; long l;
s = b;
i = b;
i = s;
l = i;
l = s;
2. Among integral types, casting is implicit if from
narrow to wide:
byte b; short s; int i; long l;
b = l;
s = i;
b = i;
b = s;
s = l;
3. Casting to a more narrow datatype requires an
explicit cast. Initial bits will be dropped.
byte b; short s; int i; long l;
b = (byte) l;
s = (short) i;
b = (byte) i;
b = (byte) s;
s = (short) l;
4. Similar rules for floating-point primitives:
float f; double d;
d = f;
f = d;
f = (double) d;
5. Integral types can be implicitly cast to floating-
point types.
byte b; short s; int i; long l; float f; double d;
f = l;
f = i;
d = i;
d = b;
d = s;
6. If a floating-point is cast to an integral,
digits after the decimal-point are dropped:
double d = 4.7;
int i = (int) d;
value of i: 4
7. char can be implicitly cast to int, long or
floating-point types
char c;
int i = c;
float f = c;
short s = c;
short s = (short) c;
8. booleans cannot be cast to any other datatype
boolean b;
int i = b;
int j = (int) b;
double d = (double) b;
short s = (short) b;