2.8 Wrapper Classes: Integer and Double

N

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:

  1. Creating Integer Objects:

    Integer numBooks = new Integer(10);

    Here, numBooks references an Integer object containing the value 10.

  2. Minimum and Maximum Values:

    • Integer.MIN_VALUE: Minimum value an int can store (-2147483648).

    • Integer.MAX_VALUE: Maximum value an int can store (2147483647).

  3. 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

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: 15

The 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:

  1. Creating Double Objects:

    Double height = new Double(6.4);

    The object height wraps the value 6.4.

  2. 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

Example:

Double distance = new Double(10.5);
System.out.println("Primitive: " + distance.doubleValue());

Output:

Primitive: 10.5

Autoboxing 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: 20

Comparing Integer and Double Wrapper Classes

FeatureIntegerDouble
Primitive Typeintdouble
Minimum ValueInteger.MIN_VALUE (-2147483648)Double.MIN_VALUE (~4.9E-324)
Maximum ValueInteger.MAX_VALUE (2147483647)Double.MAX_VALUE (~1.8E308)
Conversion Method to PrimitiveintValue()doubleValue()
Example Constructornew 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: 20

Example 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.14

Practice 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; // Incorrect

Explanation: 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

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. How do you create an Integer object?

    Use the constructor (deprecated) or valueOf() method:

    Integer num = Integer.valueOf(10);
  6. How do you create a Double object?

    Use the constructor (deprecated) or valueOf() method:

    Double num = Double.valueOf(10.5);
  7. What is autoboxing in Java?

    Autoboxing automatically converts a primitive value to its corresponding wrapper class.

    Integer num = 10; // Autoboxing from int to Integer
  8. 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
  9. 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.

  10. 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.

  11. How do you convert a string to an Integer?

    Use the Integer.parseInt() method:

    int num = Integer.parseInt("123");
  12. How do you convert a string to a Double?

    Use the Double.parseDouble() method:

    double num = Double.parseDouble("123.45");
  13. Can Integer hold null values?

    Yes, Integer can hold null values because it is an object, unlike the primitive int.

    Integer num = null;
  14. What is the default value of Integer and Double?

    When uninitialized, Integer and Double default to null because they are objects.

  15. 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
  16. 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
  17. What is the difference between parseInt() and valueOf() in Integer?

    • parseInt(): Returns a primitive int.

    • valueOf(): Returns an Integer object.

  18. What is the maximum value of Integer?

    The maximum value is defined as Integer.MAX_VALUE, which is 2,147,483,647.

  19. What is the minimum value of Integer?

    The minimum value is defined as Integer.MIN_VALUE, which is -2,147,483,648.

  20. What is the maximum value of Double?

    The maximum value is defined as Double.MAX_VALUE, approximately 1.7976931348623157e+308.

  21. What is the minimum value of Double?

    The minimum positive value is Double.MIN_VALUE, approximately 4.9e-324.

  22. What is NaN in Double?

    NaN (Not a Number) represents an undefined or unrepresentable value in floating-point calculations. Use isNaN() to check.

  23. How do you round a Double value?

    Use the Math.round() method:

    long rounded = Math.round(10.5);
  24. What is TYPE in Integer and Double?

    The TYPE field represents the primitive type the wrapper class wraps.

    Class<Integer> intType = Integer.TYPE; // int
  25. How do you convert an Integer to a string?

    Use the toString() method or String.valueOf():

    String text = Integer.toString(123);
  26. How do you convert a Double to a string?

    Use the toString() method or String.valueOf():

    String text = Double.toString(123.45);
  27. How do you convert a string to binary using Integer?

    Use the toBinaryString() method:

    String binary = Integer.toBinaryString(10); // "1010"
  28. 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<>();
  29. How do you check if a Double value is infinite?

    Use the isInfinite() method:

    boolean result = Double.isInfinite(1.0 / 0.0); // true
  30. 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
  31. 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);
  32. What is the purpose of compare() in Integer?

    Compares two primitive int values:

    int result = Integer.compare(10, 20); // -1
  33. What is the hashCode() method in Integer and Double?

    Returns the hash code for the object, often used in hashing algorithms.

  34. How do you convert a Double to an Integer?

    Cast the value explicitly or use Double.intValue():

    int num = doubleValue.intValue();
  35. What is the reverse() method in Integer?

    Reverses the bits of an integer:

    int reversed = Integer.reverse(123);
  36. How do you get the byte value of an Integer?

    Use the byteValue() method:

    byte b = new Integer(10).byteValue();
  37. Can Double represent exact decimal values?

    No, Double has precision limitations for representing exact decimal values.

  38. 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
  39. How do you parse hexadecimal values to Integer?

    Use Integer.parseInt() with a radix:

    int num = Integer.parseInt("1A", 16); // 26
  40. How do you parse scientific notation to Double?

    Use Double.parseDouble():

    double num = Double.parseDouble("1.23e3");
  41. How do you check equality for Integer and Double?

    Use the equals() method:

    boolean result = new Integer(10).equals(10);
  42. How do you convert Integer to hexadecimal?

    Use the toHexString() method:

    String hex = Integer.toHexString(255); // "ff"
  43. How do you convert Double to exponential notation?

    Use String.format():

    String exp = String.format("%.2e", 12345.67);
  44. What is the MIN_NORMAL value in Double?

    The smallest normalized positive value:

    double minNormal = Double.MIN_NORMAL;
  45. How do you perform bitwise operations on Integer?

    Use bitwise operators like &, |, ^.

  46. Can Double represent infinity?

    Yes, use Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY.

  47. How do you find the number of trailing zeros in an Integer?

    Use Integer.numberOfTrailingZeros():

    int count = Integer.numberOfTrailingZeros(16); // 4
  48. What is BYTES in Integer and Double?

    The BYTES field indicates the number of bytes used:

    int intBytes = Integer.BYTES; // 4
  49. What is the signum() method in Double?

    Returns the sign of a number (-1, 0, 1).

  50. How do you find the ceiling of a Double?

    Use Math.ceil():

    double ceil = Math.ceil(10.1); // 11.0

Leave a comment
Your email address will not be published. Required fields are marked *