A variable that can only be one of true or false two values is a Boolean (Boolean) type variable, and True and False are Boolean direct quantities. You can define a Boolean variable called state by using the following statement:
The statement initializes the variable state with a true value. You can also assign values to a Boolean variable using an assignment statement. For example, a statement,
Sets the value of the variable state to false.
Currently, we can't do much more than assign a Boolean variable, but as you'll see in the next chapter, Boolean variables are more useful when the procedure is judged, especially if we can produce a Boolean result with an expression.
There are several operators that combine Boolean values, including Boolean and (and), Boolean or (or), and Bulfei (they correspond to &&, 11, respectively). , and a comparison operator that produces a Boolean result. Instead of learning them abstractly now, let's postpone to the next chapter, where we can see how to apply them to change the order in which the programs are executed.
One thing you need to be aware of is that a Boolean variable is different from the other basic data type, it cannot be converted to any other basic type, and other basic types cannot be converted to a Boolean type.
Comparison of three methods of Java generating Boolean objects
the first common way Java generates a Boolean object is through the new operator
Boolean boolean1 = new Boolean (1==1);
The second way is to valueof by static methods
Boolean boolean1 = boolean.valueof (1==1);
The third type is the automatic boxing after JDK1.5
What is the difference between these three methods?
Read 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 results are:
Valueof:true
new Boolean:false
Auto Wrap:true
Why is that?
The reason is that the Boolean object created with new is the constant creation of an instance object, while valueof returns a static member variable in the Boolean class and does not produce a large number of identical instance variables. Automatic packaging is similar to valueof.
In fact, the JDK documentation also suggests using valueof instead of a new way to create a Boolean class object.