The wrapper classes

 

Overview

A common programming requirement is to read some numeric data from the user so it can be used in a calculation. For example, the user may be asked to enter both the quantity and the unit price of an item so the extended price (quantity times unit price) can be calculated.

While this may sound simple, there is a catch. Data entered by the user is typically a String object which can't be used in a calculation. For example, if the user enters "3" for the quantity and "5.75" for the unit price, it isn't possible to simply multiply the contents of the two String objects. Their values must first be converted to appropriate primitive types, such as int and double.

While my Keyboard class handles this conversion for you, you should know how it is done by using the Java "wrapper" classes.

 

The wrapper classes

Class name

Usage

Boolean

Encapsulates the processing of a single boolean primitive

Byte

Encapsulates the processing of a single byte primitive

Character

Encapsulates the processing of a single char primitive

Double

Encapsulates the processing of a single double primitive

Float

Encapsulates the processing of a single float primitive

Integer

Encapsulates the processing of a single int primitive

Long

Encapsulates the processing of a single long primitive

Short

Encapsulates the processing of a single short primitive

With the exception of the Character and Integer classes, the wrapper classes have names that are spelled exactly the same as their corresponding primitive type with the first letter capitalized to indicate a class.

  1. They all descend from the Object class. This means they inherit methods such as equals() and toString(). The latter makes it easy to convert a wrapper object to its equivalent string representation.

  2. All wrapper classes have a constructor that accepts a value of its corresponding primitive type. For example,

Double x = new Double(3.7);
Character y = new Character('a');
Boolean z = new Boolean(true);

would construct three wrapper objects that encapsulate a double, a char, and a boolean respectively.

Additionally, all wrapper classes except Character have a constructor to instantiate from a String. For example,

Float a = new Float("21.5");
Integer b = new Integer("15");
Boolean c = new Boolean("true");

would construct three wrapper objects that encapsulate a float, an int, and a boolean respectively.

  1. All wrapper objects are immutable. Once instantiated, a wrapper object can NEVER be changed.

  2. All wrapper classes have an instance method that will return its corresponding primitive value. The method has the general form

typeValue()

where type is the primitive type to be returned. For example, the Double class has a doubleValue() method, the Byte class has a byteValue() method, the Character class has a charValue() method, etc..

  1. All numeric wrapper classes (Byte, Short, Integer, Long, Float, and Double) have a class method that will extract (parse) its corresponding primitive value from a String. The method has the general form

parseType()

where Type is the primitive type (though capitalized) to be returned. For example, the Double class has a parseDouble() method, the Byte class has a parseByte() method, the Short class has a parseShort() method, etc..

 

public class App {
  public static void main(String[] args) {

    // Data in String form.

    String quantityAsString = "3";
    String priceAsString = "5.75";

    // Convert String data to primitive form.

    int quantity = new Integer(quantityAsString).intValue();
    double price = new Double(priceAsString).doubleValue();

    // Calculate result.

    double extendedPrice = quantity * price;

    // Convert result to String form and display it.

    String result = new Double(extendedPrice).toString();
    System.out.println("Extended price: " + result);
  }
}

Notes:

  1. Alternatively, the String data could have been converted to the primitive form by coding:

int quantity = Integer.parseInt(quantityAsString);
double price = Double.parseDouble(priceAsString);

  1. Besides converting data for you, my Keyboard class also handles exceptions (runtime errors) that might cause your program to blow-up. This program is not protected. Try changing an input string to an invalid numeric value, such as "xyz", and see what happens...

Consult the Java API for more details.

 

Other wrapper class uses

Some features of Java ONLY work with objects. For example, the classes of the Java Collections Framework (Vector, LinkedList, HashSet, etc.) can be used to organize, store, and retrieve objects. But they can't handle primitive data. The wrapper classes provide an easy way around this restriction because a primitive value can always be wrapped in an object.

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. Which of the following are not wrapper class methods?  (choose three)

  1. Long.parseLong()

  2. Char.parseChar()

  3. Float.parseFloat()

  4. Boolean.parseBoolean()

  5. Int.parseInt()

  1. What will result from attempting to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
public class App {
  public static void main(String[] args) {
    String data = "x7\"!";
    if (Character.isDigit(data.charAt(1)))
      System.out.println("Digit");
    else
      System.out.println("Not a digit");
  }
}
  1. Compilation will fail at line 3

  2. Compilation will fail at line 4

  3. Compilation is successful but a runtime error will occur

  4. Compiles and runs to display "Digit"

  5. Compiles and runs to display "Not a digit"

  1. What will result from attempting to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
public class App {
  public static void main(String[] args) {
    String data = "1,234.56";
    double tenPercent = new Double(data).doubleValue() * .10;
    System.out.println("Ten percent is: " + tenPercent);
  }
}
  1. Compilation will fail at line 3

  2. Compilation will fail at line 4

  3. Compilation is successful but a runtime error will occur

  4. The program will compile and run to display "Ten percent is: 123.456"

  5. The program will compile and run but nothing will display

  1. Assume that someString references a String having a value entered by the user. Using a static technique that does not instantiate an object, code a statement to convert and assign the contents of someString to an existing float variable named amount.