Wrapper classes in Java

Wrapper classes are basically wrappers around primitive data types. Primitive values in Java don’t have the full capabilities of objects. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type. Wrapper classes are public final i.e. cannot be extended.  Wrapper classes allow objects to be created from primitive types. The objects of all wrapper classes that can be instantiated are immutable, that is, their state cannot be changed. See the following table.

Table 1. Wrapper classes and their primitive types

 

 
 
Wrapper classes have two constructor forms (except Character class):

1) A constructor that takes the primitive type and creates an object e.g. Character(char), Integer(int)

2) A constructor that converts a String into an object e.g. Integer(“1”). It throws a NumberFormatException if the String cannot be converted to a number.

The Character class has only one public constructor, taking a primitive value as parameter. The Character class does not have a constructor that takes a String argument.

 

Converting Primitive Values to Wrapper Objects:

A constructor that takes a primitive value can be used to create wrapper objects.

Character charObj = new Character('\n');
Boolean boolObj = new Boolean(true);
Integer intObj= new Integer(2003);
Double doubleObj = new Double(3.14);

 

Converting Strings to Wrapper Objects:

A constructor that takes a String object representing the primitive value, can also be used to create wrapper objects. The constructors for the numeric wrapper types throw an unchecked NumberFormatException if the String parameter does not parse to a valid number.

Boolean boolObj1 = new Boolean("TrUe"); // case ignored: true
Boolean boolObj2 = new Boolean("XX"); // false
Integer intObj = new Integer("2003");
Double doubleObj = new Double("3.14");
Long longObj = new Long("3.14"); // NumberFormatException

 

Common Wrapper Class Utility Methods

Common Wrapper class utility methods are described below.

 

Converting Strings to Wrapper Objects:

All wrapper classes except Character, have a valueOf(String s) method which is equivalent to new Type(String s) . This method for the numeric wrapper types also throws a NumberFormatException if the String parameter is not a valid number.

static WrapperType valueOf( String s ) 
Boolean boolObj= Boolean.valueOf("false");
Integer intObj = Integer.valueOf("1949");
Double doubleObj = Double.valueOf("-3.0");

 

Converting Wrapper Objects to Strings:

Each wrapper class overrides the toString() method from the Object class. The overriding method returns a String object containing the string representation of the primitive value in the wrapper object.

String charStr = charObj.toString(); // "\n"
String boolStr = boolObj.toString(); // "true"
String intStr = intObj.toString(); // "2003"
String doubleStr = doubleObj.toString(); // "3.14"

 

Converting Primitive Values to Strings:

Each wrapper class defines a static method toString(type v) that returns the string corresponding to the primitive value of type passed as argument.

String charStr = Character.toString('\n'); // "\n"
String boolStr = Boolean.toString(true); // "true"
String intStr = Integer.toString(2003); // Base 10. "2003"
String doubleStr = Double.toString(3.14); // "3.14"

For integer primitive types, the base is assumed to be 10. For floating-point numbers, the textual representation (decimal form or scientific notation) depends on the sign and the magnitude (absolute value) of the number. The NaN value, positive infinity and negative infinity will result in the strings “NaN”, “Infinity”, and “-Infinity”, respectively.

In addition, the wrapper classes Integer and Long define overloaded toString() methods for converting integers to string representation in decimal, binary, octal, and hexadecimal notation.

 

Converting Wrapper Objects to Primitive Values:

Each wrapper class defines a typeValue() method which returns the primitive value in the wrapper object

char c = charObj1.charValue(); // '\n'
boolean b = boolObj2.booleanValue(); // true
int i = intObj1.intValue(); // 2003
double d = doubleObj1.doubleValue(); // 3.14

In addition, each numeric wrapper class defines typeValue() methods for converting the primitive value in the wrapper object to a value of any numeric primitive data type. These methods are discussed below.

 

Numeric Wrapper Classes

The numeric wrapper classes Byte, Short, Integer, Long, Float, and Double are all subclasses of the abstract class Number. Each numeric wrapper class defines an assortment of constants, including the minimum and maximum value of the corresponding primitive data type. The following code snippet retrieves the minimum and maximum values of various numeric types:

byte minByte = Byte.MIN_VALUE; // -128
int maxInt = Integer.MAX_VALUE; // 2147483647
double maxDouble = Double.MAX_VALUE; // 1.7976931348623157e+308

 

Converting any Numeric Wrapper Object to any Numeric Primitive Type:

Each numeric wrapper class defines the following set of typeValue() methods for converting the primitive value in the wrapper object to a value of any numeric primitive type:

byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()

 

The following code shows converting of values in numeric wrapper objects to any numeric primitive type:

Byte byteObj = new Byte((byte) 16); // Cast mandatory
Integer intObj = new Integer(42030);
Double doubleObj = new Double(Math.PI);
short shortVal = intObj.shortValue(); // (1)
long longVal = byteObj.longValue();
int intVal = doubleObj.intValue(); // (2) Truncation
double doubleVal = intObj.doubleValue();

Notice the potential for loss of information at (1) and (2) above, when the primitive value in a wrapper object is converted to a narrower primitive data type.

 

Converting Strings to Numeric Values:

Each numeric wrapper class defines a static method parseType(String s), which returns the primitive numeric value represented by the String object passed as argument. The Type in the method name parseType stands for the name of a numeric wrapper class, except for the name of the Integer class which is abbreviated to Int. These methods throw a NumberFormatException if the String parameter is not a valid argument.

byte value1 = Byte.parseByte("16");
int value2 = Integer.parseInt("2010"); // not parseInteger.
int value3 = Integer.parseInt("7UP"); // NumberFormatException
double value4 = Double.parseDouble("3.14");

 

Converting Integer Values to Strings in different Notations:

The wrapper classes Integer and Long provide static methods for converting integers to string representation in decimal, binary, octal, and hexadecimal notation. Some of these methods from the Integer class are listed here, but analogous methods are also defined in the Long class.

static String toBinaryString(int i)
static String toHexString(int i)
static String toOctalString(int i)

These three methods return a string representation of the integer argument as an unsigned integer in base 2, 16, and 8, respectively, with no extra leading zeroes.

static String toString(int i, int base)
static String toString(int i)

The first method returns the minus sign ‘-‘ as the first character if the integer i is negative. In all cases, it returns the string representation of the magnitude of the integer i in the specified base.

public class StringRepresentation {

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

      int negativeInt = -41; // 037777777727, -051, 0xffffffd7, -0x29
      System.out.println(" Binary:\t\t" + Integer.toBinaryString(negativeInt));
      System.out.println(" Hex:\t\t" + Integer.toHexString(negativeInt));
      System.out.println(" Octal:\t\t" + Integer.toOctalString(negativeInt));
      System.out.println(" Decimal:\t" + Integer.toString(negativeInt)); 
     
    }
}

 

Character

The Character class defines a myriad of constants, including the following which represent the minimum and the maximum value of the char type.

Character.MIN_VALUE
Character.MAX_VALUE

The Character class also defines a plethora of static methods for handling various attributes of a character, and case issues relating to characters, as defined by Unicode:

static int getNumericValue(char ch)
static boolean isLowerCase(char ch)
static boolean isUpperCase(char ch)
static boolean isTitleCase(char ch)
static boolean isDigit(char ch)
static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
static char toUpperCase(char ch)
static char toLowerCase(char ch)
static char toTitleCase(char ch)

 

Boolean

The Boolean class defines the following wrapper objects to represent the primitive values true and false, respectively:

Boolean.TRUE
Boolean.FALSE

 

Void

Although the Void class is considered as a Wrapper class, it does not wrap any primitive value and is not instantiable (i.e., has no public constructors). It just denotes the Class object representing the keyword void. The constructors and methods described above do NOT exist for the Void class although it does have the TYPE field.