Thursday, September 29, 2011

SCJP 6 Part III

Constructor
  • Character, Byte, Short
Any integer that is passed as constructor parameter must be casted because int require memory space bigger than char, byte, or short so there could be some bits loss.
Character c1 = new Character((char) 19);
  • Long, Float, Double
Any integer can be passed to long, float, or double constructor without casting because int always fits memory of long, float, or 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
Any integer that can fit char, byte, or short memory can be referenced without casting.
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
Any integer can be referenced to long, float, or 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
Any integer that can fit char, byte, or short memory can be referenced without casting.
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
Any integer must be casted to be referenced by long, float, or double because long has l, float has f, and double has d after int.
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

0 comments:

 

©2009 Stay the Same | by TNB