Table of Contents
ToggleIn 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.
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.
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
class wraps the primitive int
value into an object. This enables treating integers as objects and provides additional functionalities.
Creating Integer Objects:
Integer numBooks = new Integer(10);
Here, numBooks
references an Integer
object containing the value 10
.
Minimum and Maximum Values:
Integer.MIN_VALUE
: Minimum value an int
can store (-2147483648
).
Integer.MAX_VALUE
: Maximum value an int
can store (2147483647
).
Converting to Primitive: Use the intValue()
method to convert an Integer
object back to a primitive int
.
Integer numPencils = new Integer(32);
int numOfPencils = numPencils.intValue();
System.out.println(numOfPencils); // Output: 32
Integer x = new Integer(15);
System.out.println("Max Value: " + Integer.MAX_VALUE);
System.out.println("Primitive: " + x.intValue());
Output:
Max Value: 2147483647
Primitive: 15
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.
Creating Double Objects:
Double height = new Double(6.4);
The object height
wraps the value 6.4
.
Converting to Primitive: Use the doubleValue()
method to convert a Double
object back to a primitive double
.
Double height = new Double(6.4);
double primitiveHeight = height.doubleValue();
System.out.println(primitiveHeight); // Output: 6.4
Double distance = new Double(10.5);
System.out.println("Primitive: " + distance.doubleValue());
Output:
Primitive: 10.5
Autoboxing and unboxing streamline the conversion process between primitives and wrapper classes.
Autoboxing is the automatic conversion of a primitive data type to its corresponding wrapper class by the Java compiler.
int a = 5;
Integer b = a; // Autoboxing
System.out.println("Autoboxed: " + b);
Unboxing is the reverse process, where a wrapper object is converted back to its corresponding primitive type.
Integer x = new Integer(10);
int y = x; // Unboxing
System.out.println("Unboxed: " + y);
Integer boxed = 20; // Autoboxing
int unboxed = boxed; // Unboxing
System.out.println("Boxed: " + boxed);
System.out.println("Unboxed: " + unboxed);
Output:
Boxed: 20
Unboxed: 20
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) |
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: 20
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.14
Integer x = new Integer(10);
int y = x;
System.out.println(y);
Answer: 10
int x = 10;
Integer y = (Integer) x; // Incorrect
Explanation: Casting primitives to wrapper classes using (Integer)
is invalid. Use autoboxing instead.
Double height = new Double(5.7);
System.out.println(height.doubleValue());
Answer: 5.7
String str = "ABC";
int number = Integer.parseInt(str);
Answer: This throws NumberFormatException
because “ABC” is not a valid integer.
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.
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 Integer
for int
and Double
for double
.
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 Integer
wrapper class?
The Integer
wrapper class encapsulates the primitive int
data type in an object and provides utility methods for operations like parsing, comparison, and conversion.
What is the Double
wrapper class?
The Double
wrapper class encapsulates the primitive double
data type in an object, offering methods for mathematical operations and conversions.
How do you create an Integer
object?
Use the constructor (deprecated) or valueOf() method:
Integer num = Integer.valueOf(10);
How do you create a Double
object?
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 Integer
What is unboxing in Java?
Unboxing converts a wrapper class object back to its corresponding primitive type.
int num = new Integer(10); // Unboxing to int
What are some common methods in the Integer
class?
parseInt(String s)
: Converts a string to an int
.
toString()
: Converts the Integer
to a String
.
compareTo(Integer anotherInteger)
: Compares two Integer
objects.
What are some common methods in the Double
class?
parseDouble(String s)
: Converts a string to a double
.
isNaN()
: Checks if the value is NaN
.
toString()
: Converts the Double
to a String
.
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 Integer
hold null values?
Yes, Integer
can hold null values because it is an object, unlike the primitive int
.
Integer num = null;
What is the default value of Integer
and Double
?
When uninitialized, Integer
and Double
default to null
because they are objects.
How do you compare two Integer
objects?
Use the compareTo()
or equals()
method:
Integer a = 10;
Integer b = 20;
int result = a.compareTo(b); // -1
How do you compare two Double
objects?
Use the compareTo()
or equals()
method:
Double a = 10.5;
Double b = 20.5;
int result = a.compareTo(b); // -1
What is the difference between parseInt()
and valueOf()
in Integer
?
parseInt()
: Returns a primitive int
.
valueOf()
: Returns an Integer
object.
What is the maximum value of Integer
?
The maximum value is defined as Integer.MAX_VALUE
, which is 2,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
, approximately 1.7976931348623157e+308
.
What is the minimum value of Double
?
The minimum positive value is Double.MIN_VALUE
, approximately 4.9e-324
.
What is NaN
in Double
?
NaN
(Not a Number) represents an undefined or unrepresentable value in floating-point calculations. Use isNaN()
to check.
How do you round a Double
value?
Use the Math.round()
method:
long rounded = Math.round(10.5);
What is TYPE
in Integer
and Double
?
The TYPE
field represents the primitive type the wrapper class wraps.
Class<Integer> intType = Integer.TYPE; // int
How do you convert an Integer
to a string?
Use the toString()
method or String.valueOf()
:
String text = Integer.toString(123);
How do you convert a Double
to a string?
Use the toString()
method or String.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 Integer
or Double
objects 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 Double
value is infinite?
Use the isInfinite()
method:
boolean result = Double.isInfinite(1.0 / 0.0); // true
What is the radix parameter in Integer
methods?
The radix defines the base of numeric conversion, such as binary (2) or hexadecimal (16).
int num = Integer.parseInt("A", 16); // 10
Can you use Integer
and Double
in 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()
in Integer
?
Compares two primitive int
values:
int result = Integer.compare(10, 20); // -1
What is the hashCode()
method in Integer
and Double
?
Returns the hash code for the object, often used in hashing algorithms.
How do you convert a Double
to an Integer
?
Cast the value explicitly or use Double.intValue()
:
int num = doubleValue.intValue();
What is the reverse()
method in Integer
?
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 Double
represent exact decimal values?
No, Double
has precision limitations for representing exact decimal values.
What is the SIZE
field in Integer
?
The SIZE
field represents the number of bits used to represent the primitive type.
int size = Integer.SIZE; // 32
How do you parse hexadecimal values to Integer
?
Use Integer.parseInt()
with a radix:
int num = Integer.parseInt("1A", 16); // 26
How do you parse scientific notation to Double
?
Use Double.parseDouble()
:
double num = Double.parseDouble("1.23e3");
How do you check equality for Integer
and Double
?
Use the equals()
method:
boolean result = new Integer(10).equals(10);
How do you convert Integer
to hexadecimal?
Use the toHexString()
method:
String hex = Integer.toHexString(255); // "ff"
How do you convert Double
to exponential notation?
Use String.format()
:
String exp = String.format("%.2e", 12345.67);
What is the MIN_NORMAL
value in Double
?
The smallest normalized positive value:
double minNormal = Double.MIN_NORMAL;
How do you perform bitwise operations on Integer
?
Use bitwise operators like &
, |
, ^
.
Can Double
represent infinity?
Yes, use Double.POSITIVE_INFINITY
and Double.NEGATIVE_INFINITY
.
How do you find the number of trailing zeros in an Integer
?
Use Integer.numberOfTrailingZeros()
:
int count = Integer.numberOfTrailingZeros(16); // 4
What is BYTES
in Integer
and Double
?
The BYTES
field indicates the number of bytes used:
int intBytes = Integer.BYTES; // 4
What is the signum()
method in Double
?
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