Skip Top Navigation Bar

Using Wrapper Classes

There are times when a reference type is preferred to a primitive type. In these cases, we can use wrapper classses. A wrapper class is a class that is used to create a reference object representation of a primitive value. In this tutorial, we will explore the following wrapper classes. You can find a list of all included methods in the Java documentation:

Creating Objects of Wrapper Classes

The wrapper classes have constructors; however, since they are rarely used, these constructors are slated to be removed from the Java language and should not be used.

You can create objects of these classes by assigning the primitive value to a reference of the class type. For example, the following creates three objects:

Let's try this in the Java Playground.

Using Objects of Wrapper Classes

The compiler will implicitly convert between a primitive type and it's wrapper class equivalent. As such, you can perform arithemetic and boolean operators on these objects without having to explicitly convert between the types.

Let's try this in the Java Playground.

Converting from Reference Type to Primitive Type

To convert to a primitive type from a reference type, you simply need to assign the reference value to the corresponding primitive variable.

Let's try this in the Java Playground.

Integer Minimum and Maximum Values

The Integer class has two constants.

The range for int values are from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.

Let's try this in the Java Playground.

Wrapper Class Methods

The compiler automatically converts between the primitive types and their correspeonding object of the wrapper class, making the explicit use of the methods formly used to do these conversions unnecessary. There are a few methods that are incredibly helpful that we will call out in this tutorial.

Parsing Methods

The wrapper classes each have a method that can be used to return a representation of the String value as a primitive type.

Since these methods are static, we do not need to create an object to call these methods. They are called by using the class name.

Let's try this in the Java Playground.

In the Console Input and Output tutorial, we used the read and readln methods to obtain input from the user. When we use these methods, the type of input that is returned is String. What if you want to receive a different type of value as an input, such as an int, double, or boolean?

void main() {
    String input = readln("Enter your age: ");
    int age = Integer.parseInt(input);
    input = readln("Enter the average number of calories in a cookie: ");
    double avgCalories = Double.parseDouble(input);
    input = readln("Answer true or false. Do you like cookies?");
    boolean preferCookies = Boolean.parseBoolean(input);    
}