- Character, Byte, Short
Character c1 = new Character((char) 19);
- Long, Float, Double
Long l1 = new Long(18);
We then can conclude that if the being passed primitive is bigger, it needs casting.
new Integer(shortObject.shortValue());
new Integer((int) shortObject.doubleValue());
Primitive
- Character, Byte, Short
char c3 = 127;
Any integer that can not fit char, byte, or short memory must be casted because there could be some bits loss.
char c5 = (char) 123456;
- Long, Float, Double
long l5 = 128;
We then can conclude that if the being passed primitive is bigger, it needs casting.
float f = 90;
long l = 90;
double d = 90;
int i = (int) d;
short s = (short) f;
long l = (long) f;
Autoboxing
- Character, Byte, Short
Character c3 = 127;
Any integer that is greater than char, byte, or short bits must be casted because there could be some bits loss.
Character c5 = (char) 123456;
- Long, Float, Double
Long l5 = (long) 128;
Long l5 = 128l;
From autoboxing example above we can conclude that we must always cast the primitive to the appropriate format. This applies for char, byte, short, int, long, float, and double.
private void m(Double d) {...}
m(anIntObject); // compile error. Integer is not a Double
m(anIntObject.intValue); // compile error. Equal to Double d = 123;
m((double) anIntObject.intValue); // OK
m(anIntObject.doubleValue); // OK