Wrapper Classes: Integer and Double

Understanding Wrapper Classes: Integer and Double

  • Wrapper classes provide a way to use primitive data types (int, boolean, char… etc) as objects.
  • The Integer and Double classes are two examples of wrapper classes provided by the Java library.
  • They are part of the Java.lang package, which is automatically imported into every Java program.

Defining and Initializing Integer and Double Objects

  • To instantiate an Integer object, you would use its constructor like this: Integer i = new Integer(10);
  • To instantiate a Double object, you could use its constructor in this way: Double d = new Double(10.5);
  • Both of these constructors take a value as a parameter, which is the value the new object will store.
  • Integer and Double objects are immutable, which means that once their values are set, they cannot be changed.

The Value of Wrapper Classes

  • Wrapper classes are useful because they allow primitive data types to be used as if they were objects.
  • Each primitive data type in Java has a corresponding wrapper class.
  • These wrapper classes include methods for manipulating the encapsulated data.

Using Integer and Double Methods

  • The Integer and Double classes provide a range of useful methods for working with integer and double values.
  • For example, the compareTo() method is used to compare the value of the calling Integer or Double object with another object of the same type. It returns 0 if the values are equal, a negative number if the calling object’s value is smaller, and a positive number if it’s larger.
  • The intValue() and doubleValue() methods return the value of the calling Integer or Double object as an int or double, respectively.

Autoboxing and Unboxing

  • Autoboxing is the automatic conversion of primitive types to their corresponding object wrapper classes.
  • Unboxing is the reverse of autoboxing; it is the automatic conversion of an object of a wrapper type to its corresponding primitive type.
  • For example, the following code autoboxes the int 10 to an Integer object and then unboxes it back to an int: Integer i = 10; int j = i;

Summary

  • Understanding and effectively using wrapper classes like Integer and Double plays a key role in object-oriented programming in Java. They give programmers the flexibility to work with primitive data as if it were object data, exposing a powerful set of tools for processing this data.