MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
  • Unit 3: Class Creation
  • Unit 4: Data Collections
    • Part 1: Arrays
    • Part 2: ArrayList
      • Using Text Files
      • Wrapper Classes
      • ArrayList Methods
      • ArrayList Traversals
      • Implementing ArrayList Algorithms
      • Unit 4 Part 2 Slides
    • Part 3: 2D Arrays and Recursion

Unit 4.7: Wrapper Classes

In Java, there are times when you need to treat primitive values (like int or double) as objects. For example, the ArrayList class can only store object references, not primitive values. To solve this, Java provides wrapper classes which "wrap" a primitive value inside an object.

The Integer and Double Classes

The Integer class and Double class are part of the java.lang package (which is automatically imported).

  • Immutability: Both Integer and Double objects are immutable. This means once an object is created, its internal value cannot be changed. Any operation that seems to "change" the value actually creates a new object.
Immutability
  • Wrapper objects cannot be modified after creation. Operations that appear to change them actually result in the creation of a new object reference.

Task: Demonstrating wrapper object immutability.

Integer score = 10;
Integer originalScore = score; // Both point to the same object (value 10)

score = score + 5; // Unboxes 10, adds 5, autoboxes into a NEW object (value 15)

System.out.println(score);         // Prints 15
System.out.println(originalScore); // Prints 10 (the original object was UNCHANGED)
  • Constants: The Integer class provides useful constants:
    • Integer.MIN_VALUE: The minimum value an int can hold (-2,147,483,648).
    • Integer.MAX_VALUE: The maximum value an int can hold (2,147,483,647).

Task: Accessing wrapper class constants and constructors.

// Accessing constants
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;

// Creating wrapper objects
Integer scoreObj = new Integer(95); 
Double priceObj = new Double(19.99);

Manual Extraction

While usually handled automatically, you can manually extract values using these methods:

  • intValue(): Returns the value of an Integer as an int.
  • doubleValue(): Returns the value of a Double as a double.

Task: Manually extracting primitive values from wrapper objects.

int val = scoreObj.intValue();
double price = priceObj.doubleValue();

Autoboxing

Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes.

Automatic Wrapping
  • The Java compiler automatically wraps primitive values into their corresponding object wrapper classes when needed, such as during assignment to a wrapper variable or when passed as a method argument.

The compiler applies autoboxing when a primitive value is:

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

Task: Using autoboxing in assignment and parameters.

// 1. Assignment autoboxing
Integer myInt = 10; // compiler does: Integer.valueOf(10)

// 2. Parameter autoboxing
ArrayList<Double> prices = new ArrayList<Double>();
prices.add(19.99); // 19.99 is autoboxed into a Double object

Unboxing

Unboxing is the automatic conversion from the wrapper class back to the primitive type.

Automatic Unwrapping
  • The Java compiler automatically extracts the primitive value from a wrapper object when a primitive is expected, such as in math operations or assignments to primitive variables.

The compiler applies unboxing when a wrapper class object is:

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

Task: Using unboxing in assignments and math operations.

Integer objectVal = new Integer(5);

// 1. Assignment unboxing
int primitiveVal = objectVal; 

// 2. Math operations trigger unboxing automatically
int result = primitiveVal + objectVal; // objectVal is unboxed to 5

Autoboxing Unboxing

Integer.parseInt()

The static method int parseInt(String s) returns the String argument as a primitive int. This is useful for converting text data (like from a file) into numbers for calculation.

Task: Converting a String to a primitive int.

String input = "123";
int value = Integer.parseInt(input);
int total = value + 10; // 133

Double.parseDouble()

The static method double parseDouble(String s) returns the String argument as a primitive double.

Task: Converting a String to a primitive double.

String str = "3.14159";
double pi = Double.parseDouble(str);
double area = pi * 10 * 10;

Important Considerations

The toString() Method

Whenever you print an object using System.out.println, Java calls the toString() method. All wrapper classes override the standard Object.toString() method to return a string representation of the primitive value they enclose.

Task: Implicitly calling toString() on wrapper objects.

Integer count = 100;
System.out.println(count); // Effectively: System.out.println(count.toString());

Parsing Errors

If you attempt to parse a String that does not contain a valid number, the program will throw a NumberFormatException at runtime. Both methods are very strict and do not ignore whitespace or special symbols.

Task: Identifying common parsing errors.

// Examples of parsing failures (NumberFormatException):
int e1 = Integer.parseInt(" 42 ");   // FAIL: Leading/trailing spaces
int e2 = Integer.parseInt("1,000");  // FAIL: Commas not allowed
double e3 = Double.parseDouble("$5.50"); // FAIL: Symbols like $ not allowed
double e4 = Double.parseDouble("10.5 "); // FAIL: Trailing space

Excluded from AP CSA Exam

Exclusion Statement:
  • The five primitive data types long, short, byte, float, and char are outside the scope of the AP Computer Science A course and exam. You only need to master int, double, and boolean.
Exclusion Statement:
  • Other wrapper classes (Long, Short, Byte, Float, Boolean, Character) are not tested. For reference, here are the official documentation links for those interested:
  • Number
  • Integer
  • Float
  • Double
  • Short
  • Long
  • Boolean
Privacy Policy | Terms & Conditions