home

Primitive Types

Mathematical Operations

int Division

Dividing two ints will give you an int, not a double (Reference).

int three = 7 / 2; 

Wrapper Types

Integer

Integer myInteger;
int myInt;

// Constructors
myInteger = new Integer(1);
myInteger = new Integer("1");

// Static Methods
myInteger = Integer.valueOf(1);
myInteger = Integer.valueOf("1");

myInt = Integer.parseInt("1");
// There is no parseInt(String) method!

// Instance Methods
byte myByte = myInteger.byteValue();

Boxing and Unboxing

Passing an Exact Primitive Type for a Reference Type

void foo(Long aLong){};
foo(1L); // Java will box the primitive type

Passing a Narrow Primitive Type for a Reference Type

void foo(Long aLong){};
// This will not compile
// foo(1);
// error: incompatible types: int cannot be converted to Long

Passing Reference Type to Primitive Type

void foo(int l){}

// Passing an exact or Narrow Reference Type is fine
foo(Integer.valueOf(1));
foo(Short.valueOf((short) 1));

// Passing a Broader Type will not compile
// foo(Long.valueOf(1));