Home » Autoboxing Boolean Java

Autoboxing Boolean Java

  • by
Autoboxing Boolean Java

1. Overview

In this article, we will learn about the Autoboxing of Boolean Java. To learn more about Java topics, refer to these articles.

2. Autoboxing bool to Boolean

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

For example, converting a primitive bool to a Boolean, and so on.

Look at the following example for autoboxing.

Boolean b = false;

Converting a primitive value (a bool, for example) into an object of the corresponding wrapper class (Boolean) is called autoboxing. 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.

3. Unboxing Boolean to bool

Unboxing is all about converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class 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.

Look at the following code:

Boolean b = false;
boolean prim = b;
System.out.println(prim);

4. Autoboxing Boolean Java example

For example, we passed the boolean as a parameter to a method that expects an object of the Boolean wrapper class. Autoboxing automatically converts the boolean to Boolean at runtime using Boolean.valueOf(primitive).

 boolean primitive = false;
 print(primitive);
public static void print(Boolean wrapper) {
   System.out.println(wrapper);
}

Similarly, assigning a boolean to the variable of the Boolean wrapper class.

boolean primitive = false;
Boolean wrapper = primitive;

Autoboxing automatically converts the boolean to Boolean at runtime using Boolean.valueOf(primitive).

boolean primitive = false;
Boolean wrapper = Boolean.valueOf(primitive);

5. Conclusion

To sum up, we have learned about the Autoboxing Boolean Java with example. You can find code samples in our GitHub repository.

Leave a Reply

Your email address will not be published.