In depth analysis of the use of Boolean objects in Java programming

  • 2020-04-01 04:16:23
  • OfStack

A variable that can only be one of two values of true or false is a Boolean variable. True and false are Boolean direct quantities. You can define a Boolean variable named state with the following statement:


  boolean state=true

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


  state=false

      Set the value of the variable state to false.

      At the moment, we can't do much more than assign values to Boolean variables, but as you'll see in the next chapter, Boolean variables are more useful when programming decisions, especially when we can use expressions to produce a Boolean result.

      There are several operators that combine Boolean values, including: Boolean AND (AND), Boolean oR (oR), AND Boolean non (they correspond to & &, 11,!, respectively). , and a comparison operator that produces a Boolean result. Instead of learning them abstractly now, let's defer them until the next chapter, where we can see how to apply them to change the order of execution of the program in the exercise.

      One thing you need to be aware of is that a Boolean variable is different from other primitive data types. It cannot be converted to any other primitive type, and no other primitive type can be converted to a Boolean type.

Comparison of three Java methods for generating Boolean objects
The first common way for Java to generate a Boolean object is through the new operator


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

The second is through the static method valueOf


Boolean boolean1 = Boolean.valueOf(1==1);

The third is JDK1.5 after the automatic packing


Boolean boolean1 = 1==1;

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


Boolean[] boolean1 = new Boolean[100];
Boolean[] boolean2 = new Boolean[100];
Boolean[] boolean3 = new Boolean[100];
for (int i = 0; i < 100;i++){
  boolean1[i] = Boolean.valueOf(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;
}
System.out.println("valueOf: " + String.valueOf(boolean1[1] == boolean1[2]));
System.out.println("new Boolean: " + String.valueOf(boolean2[1] == boolean2[2]));
System.out.println("auto wrap: " + String.valueOf(boolean3[1] == boolean3[2]));

The output is:


valueOf: true
new Boolean: false
auto wrap: true

Why is that?
The reason is that a Boolean object created with new is constantly creating an instance object, whereas valueOf returns a static member variable in a Boolean class and does not produce many identical instance variables. Automatic packaging is similar to valueOf.
In fact, the JDK documentation also suggests creating Boolean class objects using valueOf instead of new.


Related articles: