[course07]02 Wrapper classes

[course07]02 Wrapper classes

A wrapper class takes either an existing object or a value of primitive type, “wraps” or “boxes” it in an object, and provides a new set of methods for that type.

Integer class

// Constructs an Integer object from an int. (Boxing.)
Integer(int value)

//Returns the value of this Integer as an int. (Unboxing.)
int intValue()

//A constant equal to the minimum value represented by an int or Integer.
Integer.MIN_VALUE

//A constant equal to the maximum value represented by an int or Integer.
Integer.MAX_VALUE

example:

Integer a = new Integer(10);
int b = a.intValue();
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);

Double class

Note

  1. The compareTo and equals methods for the Integer and Double classes are no longer part of the AP Java subset. This is probably because the later versions of Java make extensive use of autoboxing and auto-unboxing.

  2. Integer and Double objects are immutable. This means there are no mutator methods in the classes.

Autoboxing and Unboxing

Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding wrapper classes. This includes converting an int to an Integer and a double to a Double.

Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double.

comparison of wrapper class objects

Unboxing is often used in the comparison of wrapper objects of the same type. But it’s trickier than it sounds. Don’t use == to test Integer objects! You may get surprising results.

Last updated

Was this helpful?