Wrapper Classes: Integer and Double
Introduction
In Java, primitive data types like int and double are essential for handling basic operations. However, there are scenarios where these primitive types need to be treated as objects. Enter wrapper classes, such as Integer and Double. These classes provide a bridge between primitive data types and the object-oriented nature of Java.
Wrapper classes not only enable treating primitives as objects but also come with useful methods for performing various operations. This blog delves deep into “Wrapper Classes: Integer and Double,” their functionalities, and their significance in modern Java programming.
What Are Wrapper Classes?
Wrapper classes in Java allow primitive data types to be used as objects. They “wrap” the primitive value into an object, enabling its use in contexts where objects are required, such as in generic collections or methods expecting object parameters.
Why Use Wrapper Classes?
Object Manipulation: Methods or APIs often require objects rather than primitive data types.
Utility Methods: Wrapper classes provide built-in methods for converting, parsing, and manipulating values.
Autoboxing and Unboxing: Simplify code by automatically converting between primitives and their corresponding wrapper classes.
The Integer Wrapper Class
The Integer class wraps the primitive int value into an object. This enables treating integers as objects and provides additional functionalities.
Key Features:
Creating Integer Objects:
Integer numBooks = new Integer(10);Here,
numBooksreferences anIntegerobject containing the value10.Minimum and Maximum Values:
Integer.MIN_VALUE: Minimum value anintcan store (-2147483648).Integer.MAX_VALUE: Maximum value anintcan store (2147483647).
Converting to Primitive: Use the
intValue()method to convert anIntegerobject back to a primitiveint.Integer numPencils = new Integer(32); int numOfPencils = numPencils.intValue(); System.out.println(numOfPencils); // Output: 32
Example:
Integer x = new Integer(15);
System.out.println("Max Value: " + Integer.MAX_VALUE);
System.out.println("Primitive: " + x.intValue());Output:
Max Value: 2147483647
Primitive: 15The Double Wrapper Class
The Double class wraps the primitive double value into an object. Similar to Integer, it provides methods and constants for working with double-precision floating-point numbers.
Key Features:
Creating Double Objects:
Double height = new Double(6.4);The object
heightwraps the value6.4.Converting to Primitive: Use the
doubleValue()method to convert aDoubleobject back to a primitivedouble.Double height = new Double(6.4); double primitiveHeight = height.doubleValue(); System.out.println(primitiveHeight); // Output: 6.4
Example:
Double distance = new Double(10.5);
System.out.println("Primitive: " + distance.doubleValue());Output:
Primitive: 10.5Autoboxing and Unboxing
Autoboxing and unboxing streamline the conversion process between primitives and wrapper classes.
What is Autoboxing?
Autoboxing is the automatic conversion of a primitive data type to its corresponding wrapper class by the Java compiler.
Example:
int a = 5;
Integer b = a; // Autoboxing
System.out.println("Autoboxed: " + b);What is Unboxing?
Unboxing is the reverse process, where a wrapper object is converted back to its corresponding primitive type.
Example:
Integer x = new Integer(10);
int y = x; // Unboxing
System.out.println("Unboxed: " + y);Combined Example:
Integer boxed = 20; // Autoboxing
int unboxed = boxed; // Unboxing
System.out.println("Boxed: " + boxed);
System.out.println("Unboxed: " + unboxed);Output:
Boxed: 20
Unboxed: 20Comparing Integer and Double Wrapper Classes
| Feature | Integer | Double |
|---|---|---|
| Primitive Type | int | double |
| Minimum Value | Integer.MIN_VALUE (-2147483648) | Double.MIN_VALUE (~4.9E-324) |
| Maximum Value | Integer.MAX_VALUE (2147483647) | Double.MAX_VALUE (~1.8E308) |
| Conversion Method to Primitive | intValue() | doubleValue() |
| Example Constructor | new Integer(10) | new Double(10.5) |
Practical Applications
Example 1: Using Integer in a Collection
Wrapper classes allow primitives to be stored in collections such as ArrayList.
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // Autoboxing
numbers.add(20);
for (Integer num : numbers) {
System.out.println("Number: " + num);
}
}
}Output:
Number: 10
Number: 20Example 2: Parsing Strings to Numbers
Both Integer and Double provide methods to convert strings into their respective types.
public class ParseExample {
public static void main(String[] args) {
String intStr = "42";
String doubleStr = "3.14";
int intValue = Integer.parseInt(intStr);
double doubleValue = Double.parseDouble(doubleStr);
System.out.println("Parsed int: " + intValue);
System.out.println("Parsed double: " + doubleValue);
}
}Output:
Parsed int: 42
Parsed double: 3.14Practice Problems
Problem 1: What is the output?
Integer x = new Integer(10);
int y = x;
System.out.println(y);Answer: 10
Problem 2: Identify the incorrect code:
int x = 10;
Integer y = (Integer) x; // IncorrectExplanation: Casting primitives to wrapper classes using (Integer) is invalid. Use autoboxing instead.
Problem 3: Predict the output:
Double height = new Double(5.7);
System.out.println(height.doubleValue());Answer: 5.7
Problem 4: Parsing Error:
String str = "ABC";
int number = Integer.parseInt(str);Answer: This throws NumberFormatException because “ABC” is not a valid integer.
Conclusion
Wrapper classes like Integer and Double bridge the gap between primitive data types and object-oriented programming. They provide utility methods, enable object handling for primitives, and simplify conversions through autoboxing and unboxing. Understanding these classes and their applications enhances your Java programming capabilities, making your code more versatile and efficient.
Frequently Asked Questions (FAQs) About Wrapper Classes: Integer and Double
What are wrapper classes in Java?
Wrapper classes in Java provide an object representation of primitive data types, allowing primitives to be used in contexts where objects are required, such as collections or generics. Examples include
IntegerforintandDoublefordouble.Why do we use wrapper classes?
Wrapper classes are used to:
Work with collections and generics.
Perform object-oriented operations on primitive values.
Provide utility methods for parsing and converting values.
What is the
Integerwrapper class?The
Integerwrapper class encapsulates the primitiveintdata type in an object and provides utility methods for operations like parsing, comparison, and conversion.What is the
Doublewrapper class?The
Doublewrapper class encapsulates the primitivedoubledata type in an object, offering methods for mathematical operations and conversions.How do you create an
Integerobject?Use the constructor (deprecated) or valueOf() method:
Integer num = Integer.valueOf(10);How do you create a
Doubleobject?Use the constructor (deprecated) or valueOf() method:
Double num = Double.valueOf(10.5);What is autoboxing in Java?
Autoboxing automatically converts a primitive value to its corresponding wrapper class.
Integer num = 10; // Autoboxing from int to IntegerWhat is unboxing in Java?
Unboxing converts a wrapper class object back to its corresponding primitive type.
int num = new Integer(10); // Unboxing to intWhat are some common methods in the
Integerclass?parseInt(String s): Converts a string to anint.toString(): Converts theIntegerto aString.compareTo(Integer anotherInteger): Compares twoIntegerobjects.
What are some common methods in the
Doubleclass?parseDouble(String s): Converts a string to adouble.isNaN(): Checks if the value isNaN.toString(): Converts theDoubleto aString.
How do you convert a string to an
Integer?Use the
Integer.parseInt()method:int num = Integer.parseInt("123");How do you convert a string to a
Double?Use the
Double.parseDouble()method:double num = Double.parseDouble("123.45");Can
Integerhold null values?Yes,
Integercan hold null values because it is an object, unlike the primitiveint.Integer num = null;What is the default value of
IntegerandDouble?When uninitialized,
IntegerandDoubledefault tonullbecause they are objects.How do you compare two
Integerobjects?Use the
compareTo()orequals()method:Integer a = 10; Integer b = 20; int result = a.compareTo(b); // -1How do you compare two
Doubleobjects?Use the
compareTo()orequals()method:Double a = 10.5; Double b = 20.5; int result = a.compareTo(b); // -1What is the difference between
parseInt()andvalueOf()inInteger?parseInt(): Returns a primitiveint.valueOf(): Returns anIntegerobject.
What is the maximum value of
Integer?The maximum value is defined as
Integer.MAX_VALUE, which is2,147,483,647.What is the minimum value of
Integer?The minimum value is defined as
Integer.MIN_VALUE, which is-2,147,483,648.What is the maximum value of
Double?The maximum value is defined as
Double.MAX_VALUE, approximately1.7976931348623157e+308.What is the minimum value of
Double?The minimum positive value is
Double.MIN_VALUE, approximately4.9e-324.What is
NaNinDouble?NaN(Not a Number) represents an undefined or unrepresentable value in floating-point calculations. UseisNaN()to check.How do you round a
Doublevalue?Use the
Math.round()method:long rounded = Math.round(10.5);What is
TYPEinIntegerandDouble?The
TYPEfield represents the primitive type the wrapper class wraps.Class<Integer> intType = Integer.TYPE; // intHow do you convert an
Integerto a string?Use the
toString()method orString.valueOf():String text = Integer.toString(123);How do you convert a
Doubleto a string?Use the
toString()method orString.valueOf():String text = Double.toString(123.45);How do you convert a string to binary using
Integer?Use the
toBinaryString()method:String binary = Integer.toBinaryString(10); // "1010"Can
IntegerorDoubleobjects be used in collections?Yes, wrapper classes are used in collections because they are objects.
List<Integer> numbers = new ArrayList<>();How do you check if a
Doublevalue is infinite?Use the
isInfinite()method:boolean result = Double.isInfinite(1.0 / 0.0); // trueWhat is the radix parameter in
Integermethods?The radix defines the base of numeric conversion, such as binary (2) or hexadecimal (16).
int num = Integer.parseInt("A", 16); // 10Can you use
IntegerandDoublein streams?Yes, they are commonly used in streams for processing numeric data.
Stream<Integer> stream = Stream.of(1, 2, 3);What is the purpose of
compare()inInteger?Compares two primitive
intvalues:int result = Integer.compare(10, 20); // -1What is the
hashCode()method inIntegerandDouble?Returns the hash code for the object, often used in hashing algorithms.
How do you convert a
Doubleto anInteger?Cast the value explicitly or use
Double.intValue():int num = doubleValue.intValue();What is the
reverse()method inInteger?Reverses the bits of an integer:
int reversed = Integer.reverse(123);How do you get the byte value of an
Integer?Use the
byteValue()method:byte b = new Integer(10).byteValue();Can
Doublerepresent exact decimal values?No,
Doublehas precision limitations for representing exact decimal values.What is the
SIZEfield inInteger?The
SIZEfield represents the number of bits used to represent the primitive type.int size = Integer.SIZE; // 32How do you parse hexadecimal values to
Integer?Use
Integer.parseInt()with a radix:int num = Integer.parseInt("1A", 16); // 26How do you parse scientific notation to
Double?Use
Double.parseDouble():double num = Double.parseDouble("1.23e3");How do you check equality for
IntegerandDouble?Use the
equals()method:boolean result = new Integer(10).equals(10);How do you convert
Integerto hexadecimal?Use the
toHexString()method:String hex = Integer.toHexString(255); // "ff"How do you convert
Doubleto exponential notation?Use
String.format():String exp = String.format("%.2e", 12345.67);What is the
MIN_NORMALvalue inDouble?The smallest normalized positive value:
double minNormal = Double.MIN_NORMAL;How do you perform bitwise operations on
Integer?Use bitwise operators like
&,|,^.Can
Doublerepresent infinity?Yes, use
Double.POSITIVE_INFINITYandDouble.NEGATIVE_INFINITY.How do you find the number of trailing zeros in an
Integer?Use
Integer.numberOfTrailingZeros():int count = Integer.numberOfTrailingZeros(16); // 4What is
BYTESinIntegerandDouble?The
BYTESfield indicates the number of bytes used:int intBytes = Integer.BYTES; // 4What is the
signum()method inDouble?Returns the sign of a number (-1, 0, 1).
How do you find the ceiling of a
Double?Use
Math.ceil():double ceil = Math.ceil(10.1); // 11.0






