Java Boolean Conversion Instance Usage Between Boolean and boolean

  • 2021-09-24 22:21:03
  • OfStack

1. The difference between Boolean and boolean

Boolean is a class, while boolean is a basic data type, Boolean defines an object, which can be called as an object, and boolean defines a data type, which can only be called as a data type. Boolean is a Boolean type wrapper. This involves a new feature after jdk5, automatic packing.

2. Automatic packing and automatic unpacking

In many cases wrapping and unwrapping are done by the compiler itself (in this case wrapping becomes packing and unpacking is called unpacking).

Automatic boxing: Simply understood as encapsulating basic data types into object types.

Automatic unpacking: Simply understood as converting objects to basic data types again.

For example,


public  static void main (String []args){
    Boolean flag=true;
    if( flag=false){
        System.out.println("true");
    }else{
        System.out.println("false");
        }
}

Note: flag is automatically unpacked first, and the value is true.

When if is judged, flag is automatically packed and assigned as false, and then flag is automatically unpacked because it is in if conditional statement. At this time, the value is false, and the conditional judgment is not valid. Finally, false is output.

3. Conversion between Boolean and boolean

When an overloaded method is called, it will have different effects. Because the method to be invoked is determined by the static type of the parameter, the method to be invoked can be changed when converting between boolean and Boolean.

For example,


class Ideone {
    public static void main (String[] args) {
        final Boolean b = true;
        foo((boolean) b);
        foo(b);
    }
    public static void foo(boolean b) {
        System.out.println("primitive");
    }
    public static void foo(Boolean b) {
        System.out.println("wrapper");
    }
}

Knowledge point supplement:

boolean is the main type, and Boolean is a type produced after encapsulating boolean. Transform:


boolean  -" Boolean  : 
boolean b = false;
Boolean B = new Boolean(b);

Boolean  -" boolean  : 
Boolean B = new Boolean(false);
boolean b = B.booleanValue();

Related articles: