AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

2.8 Wrapper Classes: Integer and Double

Verified for the 2025 AP Computer Science A examCitation:

Java provides two categories of data types: primitive types (like int, double, boolean) and reference types (objects). Wrapper classes bridge these two worlds by providing object representations of primitive values. Understanding wrapper classes is essential for working with Java collections, methods that require objects as parameters, and utilizing the powerful functionality built into these classes.

What Are Wrapper Classes?

Wrapper classes "wrap" primitive values inside objects, allowing primitives to be used in contexts where objects are required. In the java.lang package, Java provides wrapper classes for each primitive type:

Primitive TypeWrapper Class
intInteger
doubleDouble
booleanBoolean
charCharacter
byteByte
shortShort
longLong
floatFloat

For AP Computer Science A, you'll primarily focus on the Integer and Double wrapper classes.

Integer Class

The Integer class wraps a primitive int value in an object. It's part of the java.lang package and available by default in all Java programs.

Creating Integer Objects

  • Using constructor (deprecated in newer Java versions but still on the exam)
Integer num1 = new Integer(42);
  • Using static factory method (preferred)
Integer num2 = Integer.valueOf(42);
  • Using autoboxing (most common)
Integer num3 = 42;

Important Integer Methods and Constants

  • Constructor:
    • Integer(int value) — Constructs a new Integer object representing the specified int value
  • Constants:
    • Integer.MIN_VALUE — The minimum value an int can have (-2,147,483,648)
    • Integer.MAX_VALUE — The maximum value an int can have (2,147,483,647)
  • Methods:
    • int intValue() — Returns the value of this Integer as an int
    • static Integer valueOf(int i) — Returns an Integer instance representing the specified int value
    • static int parseInt(String s) — Parses a string and returns an int primitive
    • static Integer parseInt(String s, int radix) — Parses a string in the specified radix (base)
    • String toString() — Returns a string representation of this Integer

Double Class

The Double class wraps a primitive double value in an object. Like Integer, it's also part of the java.lang package.

Creating Double Objects

// Using constructor (deprecated in newer Java versions but still on the exam)
Double num1 = new Double(3.14);

// Using static factory method (preferred)
Double num2 = Double.valueOf(3.14);

// Using autoboxing (most common)
Double num3 = 3.14;

Important Double Methods

  • Constructor:
    • Double(double value) — Constructs a new Double object representing the specified double value
  • Methods:
    • double doubleValue() — Returns the value of this Double as a double
    • static Double valueOf(double d) — Returns a Double instance representing the specified double value
    • static double parseDouble(String s) — Parses a string and returns a double primitive
    • String toString() — Returns a string representation of this Double

Autoboxing and Unboxing

Java provides automatic conversion between primitive types and their corresponding wrapper classes. This feature simplifies code and makes working with wrapper classes more convenient.

Autoboxing

Autoboxing is the automatic conversion from a primitive type to its corresponding wrapper class. The Java compiler handles this conversion behind the scenes.

// Autoboxing examples
Integer num = 42;         // Automatically converts int to Integer
Double pi = 3.14159;      // Automatically converts double to Double

// Autoboxing in method parameters
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);          // 10 is autoboxed to Integer

The Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class
  • Assigned to a variable of the corresponding wrapper class

Unboxing

Unboxing is the automatic conversion from a wrapper class to its corresponding primitive type.

// Unboxing examples
Integer wrapperNum = Integer.valueOf(25);
int primitiveNum = wrapperNum;    // Automatically converts Integer to int

Double wrapperPi = Double.valueOf(3.14);
double primitivePi = wrapperPi;   // Automatically converts Double to double

The Java compiler applies unboxing when a wrapper class object is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type
  • Assigned to a variable of the corresponding primitive type

Common Use Cases for Wrapper Classes

  1. Collections: Java collections (like ArrayList, HashMap) can only store objects, not primitives:

    ArrayList<Integer> scores = new ArrayList<>();
    scores.add(95);    // Uses autoboxing to convert int to Integer
    
  2. Utility Methods: Wrapper classes provide useful static methods for conversion and manipulation:

    int x = Integer.parseInt("42");    // Converts string to int
    String binary = Integer.toBinaryString(10);    // Converts to binary "1010"
    
  3. Handling Null Values: Unlike primitives, wrapper classes can be null:

    Integer result = calculateScore();    // Can return null if score isn't available
    if (result != null) {
        // Process the score
    }
    
  4. Method Parameters and Return Types: When you need to pass or return a primitive that could be null:

    public Integer findIndex(String name) {
        // Return null if name is not found
        return null;
    }
    

Example Code: Working with Wrapper Classes

// Converting between String and numbers
String numberStr = "123";
int num = Integer.parseInt(numberStr);
System.out.println(num + 100);  // Outputs 223

// Checking boundaries
System.out.println("Max int value: " + Integer.MAX_VALUE);
System.out.println("Min int value: " + Integer.MIN_VALUE);

// Using autoboxing and unboxing
ArrayList<Double> measurements = new ArrayList<>();
measurements.add(98.6);  // Autoboxing double to Double
double firstMeasurement = measurements.get(0);  // Unboxing Double to double

// Converting number to different formats
int value = 42;
System.out.println("Binary: " + Integer.toBinaryString(value));  // 101010
System.out.println("Hex: " + Integer.toHexString(value));       // 2a

Common Pitfalls and Best Practices

  1. Null Pointer Exceptions: Wrapper objects can be null, which causes NullPointerException if unboxed:

    Integer nullInteger = null;
    int primitive = nullInteger;  // Throws NullPointerException
    
  2. Performance Considerations: Wrapper classes create objects on the heap, which is less efficient than using primitives. Use primitives when performance is critical and wrapper classes aren't required.

  3. Equality Testing: Use equals() to compare wrapper objects, not ==:

    Integer a = 127;
    Integer b = 127;
    System.out.println(a == b);       // Might be true (due to caching)
    
    Integer c = 128;
    Integer d = 128;
    System.out.println(c == d);       // Might be false (outside cache range)
    
    System.out.println(c.equals(d));  // Always true - correct way to compare
    
  4. Integer Caching: Integer caches commonly used values (typically -128 to 127). This makes object identity comparison (==) unreliable.

When to Use Wrapper Classes vs. Primitive Types

Use wrapper classes when:

  • Working with Java collections
  • Need to represent the absence of a value (null)
  • Using methods that require object types
  • Taking advantage of helper methods in the wrapper classes

Use primitive types when:

  • Performance is critical
  • No need for null values
  • Working with basic arithmetic operations
  • Declaring local variables that don't need object functionality

Wrapper classes play a vital role in Java programming by bridging the gap between the primitive type system and the object-oriented world. Understanding when and how to use Integer and Double will help you write more flexible and powerful Java code.

Key Terms to Review (5)

Autoboxing: Autoboxing is the automatic conversion of a primitive data type to its corresponding wrapper class object. For example, when an int is assigned to an Integer object, autoboxing occurs.
Integer class: The Integer class is a built-in class in Java that represents integer values. It provides methods to perform various operations on integers, such as converting them to strings or performing arithmetic calculations.
Primitive data types: Primitive data types are basic data types that are built into a programming language and represent simple values. They include integers, floating-point numbers, characters, booleans, and more.
Reference Data Type: A reference data type is a data type that refers to an object in memory rather than directly storing the value. It stores the memory address where the object is located.
Unboxing: Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive data type. For example, when an Integer object is assigned to an int variable, unboxing occurs.