Java. Autoboxing and auto unboxing

Autoboxing and auto unboxing. General concepts. Using in assignment (=) and in methods. Examples

Before studying this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other resources:

1. The concept of autoboxing and auto-unboxing. Cases of occurrence and benefits of use

Autoboxing and auto-unboxing have been introduced in Java since JDK 5.
Autoboxing is the process of automatically converting (encapsulating) a primitive type (int, double, boolean, etc.) into its corresponding type wrapper (Integer, Double, Boolean, etc.) when it is required to obtain an object of this type.
For example, if you need to get an object for the primitive type int, it will be an object of type Integer. Accordingly, converting int to Integer is called autoboxing.
Auto-unboxing is the process of automatically extracting a value of a primitive type (int, char, float, etc.) from a type wrapper (Integer, Character, Float, etc.) at the moment when you need to get its value.

For example, if a value of the primitive type float is obtained from a wrapper of type Float, then this process occurs automatically and is called auto-unboxing.
Auto-unboxing avoids calling methods like intValue() or doubleValue().

Autoboxing and auto-unboxing are performed in the following cases:

  • when performing an assignment (=);
  • when passing a parameter to a method;
  • when returning from a method;
  • when implicitly converted in expressions.

Autoboxing and auto-unboxing provide the following benefits:

  • there is no need for manual boxing and unboxing of values;
  • simplifies the implementation of conversion algorithms between primitive types and wrapper types;
  • reduces the number of errors that can occur based on this context;
  • work with Java collections is greatly facilitated;
  • autoboxing avoids the explicit creation of an object.

 

2. Features of the implementation of autoboxing when assigning (=). Example

When performing autoboxing, you do not need to create an object using the new operator. Autoboxing is performed when an assignment operator is called, which might look like this

obj = value;

or

Type obj = value;

here

  • Type – some wrapper type, which is a wrapper over the primitive type, which corresponds to the value value. Java implements the following wrapper types to represent basic primitive types: Double, Float, Long, Integer, Short, Byte, Character, Boolean. You can read more about Java data types here (2.1…);
  • obj – object (instance) of the wrapper type (Integer, Double, Character, etc.);
  • value – a value of a primitive type (int, double, char, etc.), which is equivalent to the type of the obj object.

 

3. Examples of autoboxing when assigned (=)

The example demonstrates the autoboxing process for different types.

// Autoboxing
Boolean B = true; // Boolean <= boolean

int i = 28;
Integer objInt = i; // Integer <= int

float f = 7.58f;
Float objFloat = f; // Float <= float

double x = 19230.338;
Double objDouble;
objDouble = x; // Double <= double

Character objChar = '+'; // Character <= char

short t = 255;
Short objShort = t; // Short <= short

long l = 2323023933L;
Long objLong = l; // Long <= long

 

4. Examples of auto-unboxing when assigned (=)

The assignment of values of the wrapper types Integer, Character, Boolean, Long to values of the primitive types int, char, boolean, long is demonstrated.

// Auto-unboxing on assignment.
Integer objI = 25;
int i = objI; // int <= Integer

Character objC = 'f';
char c;
c = objC; // char <= Character

Boolean objB = false;
boolean b = objB; // boolean <= Boolean

Long objL = 2322432342342l;
long l = objL; // long <= Long

 

5. Auto-boxing and auto-unboxing when passing a parameter to a method. Examples

Autoboxing occurs automatically whenever a primitive type is converted to an object. Autounboxing occurs automatically when an object is converted to a primitive type.
Thus, these two processes occur in cases where the method receives an argument or the method returns some value. There are 4 cases here:

  • when a primitive type parameter is declared in a method, and the method receives a wrapper type argument. In this case, auto-unboxing occurs;
  • when a wrapper type parameter is declared in a method and the method receives a primitive type argument. In this case, autoboxing occurs;
  • when a primitive type is returned in the method declaration (by the return statement), and the method body returns the wrapper type. In this case, auto-unboxing occurs;
  • when the wrapper type is returned in the method declaration, and the method returns a primitive type. In this case, autoboxing takes place.

 

5.1. Return from a method of a primitive type. Auto unboxing

Demonstrates the Max() function, which determines the maximum between two values of type Integer, which is a wrapper type. The function returns a value of the primitive type int. In this case, the value of type Integer is auto-unpacked into a value of type int.

public class TrainAutoPacking {

  // Auto-unboxing. Method determines the maximum of two values
  static int Max(Integer a, Integer b) {
    Integer max = a;
    if (a<b)
      max = b;
    return max; // Auto-unboxing int <= Integer
  }

  public static void main(String[] args) {

    // 1. Declare variables of wrapper type
    Integer x = 25;
    Integer y = 30;

    // 2. Call the function, auto-unboxing takes place.
    int z = Max(x, y); // int <= Integer - auto-unboxing

    System.out.println(z); // 30
  }
}

 

5.2. Return from a method of the wrapper type. Autoboxing

The example declares the Min() method, which determines the minimum value between two integer values of the primitive type int. The method returns an object of type Integer, which is a wrapper type for int. On return, the value of type int is auto-boxed into a value of type Integer.

public class TrainAutoPacking {

  // Auto-unboxing.
  // The method returns the minimum of two values of the primitive type
  static Integer Min(int a, int b) {
    int min = a;
    if (a>b)
      min = b;
    return min; // Auto-packing on return
  }

  public static void main(String[] args) {

    // Returning a value from a method. Autoboxing
    int x = 30;
    int y = 22;
    Integer z;
    z = Min(x, y); // Integer <= int - autoboxing

    System.out.println(z); // 22
  }
}

 

5.3. Passing a primitive type argument to the method that receives the wrapper type parameter. Auto-boxing

The example declares a method that reverses a number. When a number is passed to a method, the primitive type long is autoboxed into the Long wrapper type.

public class TrainAutoPacking {

  // Auto-boxing.
  // The method returns a number read backwards: 12345 => 54321
  static long ReverseNumber(Long number) {

    // 1. Get a copy of the input parameter
    Long t = number;

    // 2. The loop for calculating the new value of number
    number = 0L;
    while (t>0) {
      number = number * 10 + t % 10;
      t /= 10;
    }

    // 3. Return the result
    return number;
  }

  public static void main(String[] args) {

    // Returning a value from a method. Autoboxing
    // 1. Given number
    long n = 12345L;

    // 2. Calling a method,
    // type long is automatically boxed into type Long
    long res = ReverseNumber(n);

    // 3. Display the result
    System.out.println(res); // 54321
  }
}

 

5.4. Passing a wrapper type argument to a method that receives a primitive type parameter. Auto-unboxing

The NumDigits() method is declared, which determines the number of digits in a number. The method receives a value of the primitive type short as an input parameter. When the method is called from the main() function, a value of the Short wrapper type is passed to it. With such a call, the auto-unboxing mechanism is launched.

public class TrainAutoPacking {

  // A method that determines the number of digits in a number.
  static int NumDigits(short number) {
    int k = 0;
    while (number>0) {
      k++;
      number /= 10;
    }
  return k;
  }

  public static void main(String[] args) {
    // 1. Specified number
    Short num = 21335;

    // 2. Call the function NumDigits(),
    // auto-unboxing occurs short <= Short
    int res = NumDigits(num);

    // 3. Display the result
    System.out.println(res); // 5
  }
}

 


Related topics