CS 1713: Wrapper Classes

The Java Integer class

The int is the simplest of all the Java data types.
It is a primitive type, that means that it is not an object and there are no methods associated with it.

The Integer class serves two purposes.

You are probably already familiar with the parseInt method from the Integer class. It can be used to convert a String to an integer as in the following example:
String s = "12345";
int x = Integer.parseInt(s);
Note that this method can throw a NumberFormatException if the string does not represent an integer. The string is not allows to contain an leading or trailing blanks. You can use the trim method from the String class to eliminate any leading or trailing white space:
String s = "   12345  \n";
int x = Integer.parseInt(s.trim());

The Integer class also contains two important constants:
MAX_VALUE and MIN_VALUE.

System.out.println("The largest possible int in Java is "+Integer.MAX_INT);
System.out.println("The smallest possible int in Java is "+Integer.MIN_INT);
The values of these are 231-1 and -231.

The other use of the Integer class is to create an object that presents a single integer.

int x = 5;
int y = 6;
Integer x1 = new Integer(x);
Integer y1 = new Integer(y);
System.out.println("x = "+x+" and y = "+y);
System.out.println("x1 = "+x1.intValue()+ and y1 = "+y.intValue());
x = y;
System.out.println("x = "+x+" and y = "+y);
System.out.println("x1 = "+x1.intValue()+ and y1 = "+y.intValue());
This produces the following output:
x = 5 and y = 6
x1 = 5 and y1 = 6
x = 6 and y = 6
x1 = 5 and y1 = 6
There are no methods for changing the value of an Integer object once it has bee created. Other way of saying this is that Integers are immutable.

The Integer class can be used to create an ArrayList containing integers. Recall that you cannot have an ArrayList of primitives, only of objects.

Example: Create an ArrayList and add 100 randomly generated Integer objects to it.

   Random rand = new Random( );
   ArrayList<Integer> values = new ArrayList<Integer>( );
   for (int i = 0; i < 100; i++)
      values.add(rand.nextInt( ));
This example shows a special feature of the wrapper classes referred to as auto boxing.
rand.nextInt() produces an int, not an Integer, but Java can figure out that the add method requires and Integer and automatically puts a box (wrapper) around the parameter.

Java can also do auto unboxing. It is not recommended that you use the auto boxing or unboxing features.


Other wrapper classes

Each of the primitive types has a corresponding wrapper class. The ones that are most important (other than Integer are Double and Character.

The most useful method of the Double class is the parseDouble method:

String s = "123.456";
double x = Double.parseDouble(s);
The parseDouble method can throw a NumberFormatException.

The Character class has a number of useful static methods:

and many more.