Overview: 2.8.0

  • Each primitive has a built-in object type
    • called a wrapper class
    • int -> Integer
    • double -> Double
  • You may need to use them to give a primitive type to a method expecting an object
  • Have special values and methods
  • Before Java 9, call the constructor for a wrapper class
    • deprecated in Java 9+
      • Means this isn’t the ideal way to do things
  • After Java 9, just set it equal to a value
// Old way (Before Java 9)
Integer i = new Integer(33);

// New way (After Java 9)
Integer i = 33;

The AP CS A exam uses Java 7, so the constructor is acceptable

Integer minimum and maximum values

  • Integer has special values for the maximum and minimum values which can be stored
  • Integers are represented in 32 bits of space
    • 31 bits are used to represent the number
    • 1 bit is used to represent the “sign” (positive or negative) of the number

Overflow and Underflow

  • Java will return the maximum if you subtract 1 from the minimum value
    • called Underflow
    • maximum + 1 returns the minimum
      • Called Overflow
    • Similar to how odometers work

Autoboxing and Unboxing

  • Autoboxing is the automatic conversion of primitive types into wrapper classes
Integer i = 33; // autoboxing converts primitive 33 into an object

// Uses an Integer Object specific method to convert an integer value into a long
// Long is a 64 bit integer (not covered on the exam); see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
long intToLong(Integer myNumber) {
    return myNumber.longValue();
}
// ...later in the code

int myInt = 37;

long myIntAsLong = intToLong(myInt); // autoboxing happens here too
  • Unboxing is the automatic conversion from a wrapper class to a primitive type
    • Happens when java expects a primitive and receives an object
Integer myInt = 99; // autoboxing - convert to Object
int myOtherInt = myInt; // Unboxing - convert to primitive

Useful string methods

  • Integer.intValue returns the primitive value
    • Double.doubleValue
  • Integer.parseInt and Double.parseDouble
    • Converts the string version of a number into an int or double

Summary: 2.8.2

  • Integer and Double are wrapper classes to create objects from primitives
  • Autoboxing is the automatic conversion of primitive types into the corresponding wrapper class
    • Autoboxing is applied when:
      • A primitive is passed as a parameter to a method expecting a wrapper object
      • A primitive is assigned to a variable of the wrapper class type
  • Unboxing is the automatic conversion of a wrapper class into a primitive type
    • Unboxing is applied when:
      • A wrapper class object is passed as a parameter to a method expecting a primitive
      • A wrapper class object is assigned as the value of a primitive of the corresponding type