Wednesday, June 03, 2009

Number types in Java


Boxing: If you use a primitive type where a Object is expected, then the compiler will auto-box it into a wrapper class. Similarly if a wrapper object is used where a primitive is expected, the compiler will auto-unbox it.

Integer x = 10; // 10 boxed into wrapper class instance x
Integer y = 20; // 20 boxed into wrapper class instance y
System.out.println(x+y); // x and y unboxed to primitives so that they can be added by passing them to the + operator

Advantages of using a Object-wrapper-of-a-primitive over using a primitive
1. Argument to methods that expect a Object such as the collection interfaces
2. To use constants defined in these wrapper classes such as min_value and max_value
3. To convert primitives to wrapper classes using methods exposed in wrapper classes

Methods exposed by sub-classes of Number
xxxValue() e.g. byteValue() returns the wrapped primitive value
static Byte | Short | Integer | Long | Float | Double valueOf (byte, short, int, long, float, double) -> primitive to wrapped type
static Byte | Short | Integer | Long | Float | Double valueOf (String) -> String to Wrapped type
int compareTo(Byte | Short | Integer | Long | Float | Double) - to compare Number instances
boolean equals(Object)
static String toString(int i), String toString() to convert primitive to String

No comments: