A variable that can only have one of two values, true or false, is a Boolean type variable, and true and false are Boolean direct quantities. You can define a Boolean variable named state using the following statement:
boolean state=true
This statement initializes the variable state with a true value. You can also use the assignment statement to assign a value to a boolean variable. For example, the statement,
state=false
Set the value of the variable state to false.
Currently, we can't do much more than assign values to Boolean variables, but as you'll see in the next chapter, Boolean variables are useful when making decisions in a program, especially when we can use expressions to generate a It is more useful for boolean results.
There are several operators that combine Boolean values, including: Boolean AND (AND), Boolean OR (oR), and Boolean NOT (which correspond to &&, 11, and !, respectively), as well as comparison operators that produce boolean results. Rather than learning them in the abstract now, we defer to the next chapter, where we can see in exercises how to apply them to change the order of execution of a program.
One thing you need to note is that the boolean variable is different from other basic data types. It cannot be converted to any other basic type, and other basic types cannot be converted to the boolean type.
Comparison of three methods for generating Boolean objects in Java
The first common way Java generates Boolean objects 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 type is automatic boxing 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 ] = 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: truenew Boolean: falseauto wrap: true
Why is this happening?
The reason is that the Boolean object created with new continuously creates a new instance object, while valueOf returns the static member variables in the Boolean class and does not generate a large number of identical 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.