Java - Numeric Wrapper Classes

What are Numeric Wrapper Classes?

Byte, Short, Integer, Long, Float, and Double classes are numeric wrapper classes.

They are all inherited from the Number class.

The Number class is abstract. You cannot create an object of the Number class.

Constants

All numeric wrapper classes contain several useful constants.

Their MIN_VALUE and MAX_VALUE constants represent the minimum and maximum values that can be represented by their corresponding primitive type.

For example, Byte.MIN_VALUE constant is -128 and Byte.MAX_VALUE constant is 127.

They have a SIZE constant that represents the size in bits that a variable of the corresponding primitive type occupies. For example, Byte.SIZE is 8 and Integer.SIZE is 32.

Methods

The Number class contains six methods.

They are named xxxValue() where xxx is one of the six primitive data types (byte, short, int, long, float, and double).

The return type of the methods is the same as xxx.

For example, the byteValue() method returns a byte, the intValue() method returns an int, etc.

The following snippet shows how to retrieve different primate type values from a numeric wrapper object:

Demo

public class Main {
  public static void main(String[] args) {
    // Creates an Integer object
    Integer intObj = Integer.valueOf(100);

    // Gets byte from Integer
    byte b = intObj.byteValue();

    // Gets double from Integer
    double dd = intObj.doubleValue();
    System.out.println("intObj = " + intObj);
    System.out.println("byte from intObj = " + b);
    System.out.println("double from intObj = " + dd);

    // Creates a Double object
    Double doubleObj = Double.valueOf("12345.67");

    // Gets different types of primitive values from Double
    double d = doubleObj.doubleValue();
    float f = doubleObj.floatValue();
    int i = doubleObj.intValue();
    long l = doubleObj.longValue();

    System.out.println("doubleObj = " + doubleObj);
    System.out.println("double from doubleObj = " + d);
    System.out.println("float from doubleObj = " + f);
    System.out.println("int from doubleObj = " + i);
    System.out.println("long from doubleObj = " + l);
  }/*from  w  w  w  .  j ava 2  s . c om*/
}

Result

Related Topics