Java Number Operations

Number Wrapper Classes

In "Converting Between Numbers and Java Strings" you saw the use of the primitive wrapper classes to parse Java Strings and to convert numbers to Java Strings via toString(). Each primitive data type has a corresponding wrapper class located in the java.lang package.

                   Treat Primitives as Objects

The wrapper classes are primarily used to store primitive data types in objects so they can be handled by classes that only work with objects. For example, the Java Collections API has many data structure classes such as ArrayList and HashMap that only work with objects—in order to store a primitive number in one of these collections, you must first wrap it.

Example:

 ArrayList list = new ArrayList();
 int age1 = 25;
 int age2 = 20;
 list.add(new Integer(age1)); //wrap age1 in Integer
 list.add(new Integer(age2)); //wrap age2 in Integer

Autoboxing

Prior to Java 5.0 Tiger, a developer had to manually convert primitives to wrappers and vice versa. One of the syntactic shortcuts added in Java 5.0 was autoboxing (automatically converting primitives to wrappers) and auto-unboxing (automatically converting wrappers to numbers).

To autobox, simply assign a primitive value to an appropriate wrapper object. To auto-unbox, assign a wrapper object reference to an appropriate primitive variable. The compiler takes care of the plumbing.

 Integer a = 55; //autobox int to Integer
 float f = new Float(22.5f); //auto-unbox Float to float
 long l = a; //auto-unbox Integer to long 
  • Math Class

    No, this section does not refer to Mr. Johnson's ninth grade algebra class but, instead, to java.lang.Math, which provides methods for basic numeric operations beyond simple arithmetic. Powers, rounding, square roots, maximums, and minimums are a few of the operations it handles. We will look at two typical uses of Math.

  • Computing Square Roots

    Since Math.sqrt() is static, you don't have to create an instance of Math in order to call it.

    Example:

 double d = 16.0;
 double r = Math.sqrt(d); //r == 4.0

Rounding Numbers

If you have a floating point number that must be rounded "half up," then you can use Math.round(). If you need more complex rounding logic, you should use BigDecimal.

Example:

 int a = Math.round(25.4f); //a is set to 25
 int b = Math.round(25.5f); //b is set to 26 

In this tutorial, we reviewed the fundamentals of working with numbers in Java. This, of course, is just the beginning. In future tutorials we will examine BigDecimal, BigInteger, and random number generation.

<< Back