Wrapper Classes in Java

Wrapper ClassesAutoboxingEnum

In the previous blog we learned about the ArrayList in Java. If you want to know about the ArrayList visit the blog ArrayList in Java. In this blog, we will learn about the Wrapper classes in Java. Wrapper Classes are the classes that provide a mechanism to convert primitive to object and object to primitive.

Wrapper Classes and Autoboxing

Suppose we want to convert the primitive type i.e. int to an object. All primitive types have classes. For example, the class Integer belongs to the primitive type int. These classes are called Wrapper. The wrapper classes have names like Integer, Long, Float, Double, Short, Byte, Character, and Boolean. The wrapper classes are immutable i.e. we cannot change the value of it after the wrapper is constructed. The Wrapper classes are also final due to which we cannot subclass them. Suppose we want the array list of int. But unfortunately, we cannot use the primitive type inside the angle brackets For example we cannot write:

e.g.

var atrowelList = new ArrayList<int>;

In order to define an array list of integers, Integers come into the picture. For example

var atrowelList = new ArrayList<Integer>();

The above statement is a valid statement. It is fine to declare an array list of Integer objects. We can easily add elements into the array list of integer objects using add() method. For example

atrowelList.add(5);

The above call is automatically translated to:

atrowelList.add(Integer.valueOf(5));

This is called autoboxing. On the other hand when we assign an Integer object to an int value, then it is automatically unboxed. The compiler translates

int atrowelNo = atrowelList.get(i);

into:

int atrowelNo = atrowelList.get(i).intValue();

Automatic boxing and Unboxing also can work with arithmetic expressions. We can apply the increment operator to a wrapper reference:

Integer atrowelNo = 3;
atrowelNo++;

Most of the time we get confused between the primitive types and their wrapper is the same. But there is a slight difference between these two i.e. identity. As we know that the == operator, when applied to wrapper objects, only tests whether the objects have identical memory locations.

Integer no1 = 1000;
Integer no2 = 1000;
if (no1 == no2) . . .

The above comparison will fail. But if Java implementation chooses, to wrap commonly occurring values into identical objects, then the comparison may succeed. We don’t want such a type of ambiguity. The solution for this is to use the equals() method when we want to compare wrapper object. There are the following things to be remembered for autoboxing:

  1. If the wrapper reference is null, then it is possible that autounboxing will throw a Null Pointer Exception. For example:
  2. Integer no = null;
    System.out.println(2 * no);
  3. If we mix Integer and Double types in a conditional expression, then the Integer value is unboxed, promoted to double, and boxed into a Double. For example
  4. Integer n = 1;
    Double x = 2.0;
    System.out.println(true ? n : x);

If we want to convert a string into an int then we can do the following way:

int value = Integer.parseInt(str);

In the above example we are trying to convert the string into integer. We have used the parseInt method which is a static method of the Integer class. Following are other methods:

MethodsDescription
int intValue()It returns the value of this Integer object as an int
static String toString(int intValue)It returns a new String object representing the number intValue in base 10.
static String toString(int intValue, int radix)It allows us to return a representation of the number intValue in the base specified by the radix parameter.
static int parseInt(String str)

static int parseInt(String str, int radix)

This method returns the integer whose digits are contained in the string str. The string must represent an integer in base 10 for the first method or in the base given by the radix parameter for the second method.
static Integer valueOf(String str)

static Integer valueOf(String str, int radix)

It returns a new Integer object initialized to the integer whose digits are contained in the string str. The string must represent an integer in base 10 for the first method or in the base given by the radix parameter for the second method.

Methods with a Variable Number of Parameters in Java

Java provide methods that can be called with the variable number of parameters. They are also called as varargs methods. For example, we are already familiar with the printf:

System.out.printf("%d", no);

And also

System.out.printf("%d %s", no, "widgets");

Both statements call the same method even though one has 2 parameters and the other has 3 parameters. The definition of printf is as follows:

public class PrintStream{
  public PrintStream printf(String fmtStr, Object... args) {
  }

The printf() method receives two parameters i.e. format string and an Object[ ] array that holds the other parameters. The Object parameter type is the same as the Object[ ]. The compiler requires to transform each call to printf, bundling the parameters into an array and autoboxing as necessary:

System.out.printf("%d %s", new Object[] { new Integer(no),"widgets" } );

We can also define our own methods with variable parameters, and we can also specify any type for the parameters, even a primitive type.


Java Enums

An Enum is a class that represents a group of constants like final variables. We can define the enum type in the following way:

public enum Size { EXTRASMALL,SMALL, MEDIUM, LARGE, EXTRALARGE }

The type defined in the declaration is nothing but the class. It is not possible to construct new objects as the class has 5 instances. For this reason, we will not use equals for values of enumerated types. We can simply use == to compare them. If we want we can add constructors, methods, and fields to the enumerated type. The constructors will only invoke when the enumerated constants will be constructed. For example:

public enum Size{
  EXTRASMALL("XS"), SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
  private String abbr;
  private Size(String abbr) {
    this.abbr = abbr;
  }
  public String getAbbr() {
    return abbr;
  }
}

The constructor of an enumeration is always private. As we can see in the above example we have defined the constructor as private. It is not allowed to use a public or protected modifier. If we use it then the compiler will give a syntax error. All enumerated types are subclasses of the class Enum. They inherit several methods from that class. The most useful method is the toString() method, which returns the name of the enumerated constant. For example, Size.EXTRASMALL.toString() returns the string "EXTRA SMALL". The reverse of the toString() method is the valueOf() method. For example

Size size = Enum.valueOf(Size.class, "EXTRASMALL");

The above statement sets size to Size.SMALL. Each enumerated type has a static values method which returns an array of all values of the enumeration. For example

Size[] values = Size.values();

The above statement returns the array with elements Size.EXTRASMALL, Size.SMALL, Size.MEDIUM, Size.LARGE, and Size.EXTRALARGE.

import java.util.*;
public class EnumTestEX{
  public static void main(String[] args){
    var in = new Scanner(System.in);
    System.out.print("Enter a size: (EXTRASMALL, SMALL, MEDIUM, LARGE, EXTRALARGE) ");
    String atrowelInput = in.next().toUpperCase();
    Size size = Enum.valueOf(Size.class, atrowelInput);
    System.out.println("size=" + size);
    System.out.println("
abbreviation=" + size.getAbbr());
    if (size == Size.EXTRALARGE){
      System.out.println("Good job");
    }
  }
  enum Size{
    EXTRASMALL("XS"), SMALL("S"), MEDIUM("M"), LARGE("L"),  EXTRALARGE("XL");
    private Size(String abbr) {
      this.abbr = abbr;
    }
    public String getAbbr() {
      return abbr;
    }
    private String abbr;
  }
Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.