Wrapper Classes in Java

Wrapper classes in Java are classes that allow primitive data types to be accessed as objects.

Wrapper classes in Java

There are eight wrapper classes in Java, one for each primitive data type:

Wrapper classes in Java are useful when we need to treat primitives as objects, for example when we need to store them in a collection that only supports objects.

Common methods of Java wrapper classes

Following are some common methods of the wrapper classes:

valueOf()

This method returns a wrapper object that contains the value of the specified primitive. For example:

int primitiveInt = 10;
Integer wrapperInt = Integer.valueOf(primitiveInt);

parseXXX()

These methods parse a string and return the corresponding primitive value. For example:

String strInt = "123";
int primitiveInt = Integer.parseInt(strInt);

XXXValue()

These methods return the primitive value of the wrapper object. For example:

Integer wrapperInt = new Integer(123);
int primitiveInt = wrapperInt.intValue();

compareTo()

This method compares the value of the wrapper object to the value of another wrapper object or a primitive. It returns a negative integer if the value is less, a positive integer if the value is greater, and 0 if the values are equal. For example:

Integer wrapperInt1 = new Integer(123);
Integer wrapperInt2 = new Integer(456);
int result = wrapperInt1.compareTo(wrapperInt2);  // result is -1

equals()

This method compares the value of the wrapper object to the value of another object, and returns true if they are equal, and false otherwise. For example:

Integer wrapperInt1 = new Integer(123);
Integer wrapperInt2 = new Integer(123);
boolean result = wrapperInt1.equals(wrapperInt2);  // result is true

toString()

This method returns a string representation of the wrapper object. For example:

Integer wrapperInt = new Integer(123);
String str = wrapperInt.toString();  // str is "123"

Sharing Is Caring: