SoFunction
Updated on 2025-03-02

In-depth analysis of the application of boolean objects in Java programming

A variable that can only be one of the two values ​​true or false is a boolean type variable, and true and false are boolean direct quantities. You can use the following statement to define a Boolean variable named state:

  boolean state=true

This statement initializes the variable state with a true value. You can also use the assignment statement to assign values ​​to a boolean variable. For example, a statement,

  state=false

Set the value of the variable state to false.

At present, we cannot do more operations other than assigning values ​​to Boolean variables, but as you will see in the next chapter, Boolean variables are more useful when making decisions on programs, especially when we can use expressions to generate a boolean result.

There are several operators that combine Boolean numeric values, including: Boolean and (AND), Boolean or (oR) and Boolean non (they correspond to &&, 11, !, respectively), and comparison operators that produce boolean results. Rather than learning them abstractly now, let's postpone it to the next chapter, where we can see in practice how to apply them to change the order in which the program is executed.

One thing you need to note is that boolean type variables are different from other basic data types. They cannot be converted to any other basic type, and other basic types cannot be converted to boolean type.

Comparison of three ways to generate Boolean objects in Java
The first common way to generate Boolean objects in Java is through the new operator

Boolean boolean1 = new Boolean(1==1);

The second method is through the static method valueOf

Boolean boolean1 = (1==1);

The third type is automatic packing after JDK1.5

Boolean boolean1 = 1==1;

What is the difference between these three methods?
Let's look at a piece of code first

Boolean[] boolean1 = new Boolean[100];
Boolean[] boolean2 = new Boolean[100];
Boolean[] boolean3 = new Boolean[100];
for (int i = 0; i < 100;i++){
  boolean1[i] = (1==1);
}
for (int i = 0;i < 100;i++){
  boolean2[i] = new Boolean(1==1);
}
for (int i = 0; i < 100;i++){
  boolean3[i] = 1==1;
}
("valueOf: " + (boolean1[1] == boolean1[2]));
("new Boolean: " + (boolean2[1] == boolean2[2]));
("auto wrap: " + (boolean3[1] == boolean3[2]));

The output result is:

valueOf: true
new Boolean: false
auto wrap: true

Why is this happening?
The reason is that the Boolean object created with new is constantly creating a new instance object, while valueOf returns static member variables in the Boolean class, and will not generate a large number of the same instance variables. Automatic wrapping is similar to valueOf.
In fact, the jdk document also recommends using valueOf instead of new to create Boolean class objects.