Detailed Explanation of Java Boolean Initialization Mode

  • 2021-11-02 00:41:24
  • OfStack

Java Boolean initialization mode

1. Boolean (String boolString);

Initialized as a string, true only if the string is "true" (case-insensitive, tRue or the like); Other strings to complete initialization are false.


Boolean dpBoolean = new Boolean("ok");
System.out.println(dpBoolean);
 Results: false
Boolean dpBoolean = new Boolean("false");
System.out.println(dpBoolean);
 Results: false
Boolean dpBoolean = new Boolean("true");
System.out.println(dpBoolean);
 Results: true
Boolean dpBoolean = new Boolean("tRue");
System.out.println(dpBoolean);
 Results: true

2. Boolean (boolean boolValue);

If true or false is used for initialization, only true is true;;


Boolean dpBoolean = new Boolean(null);
System.out.println(dpBoolean);
 Results: false
Boolean dpBoolean = new Boolean(false);
System.out.println(dpBoolean);
 Results: false
Boolean dpBoolean = new Boolean(true);
System.out.println(dpBoolean);
 Results: true

3. If you define an array of Boolean objects

The default initialization value is null; When defining boolean array, the default initialization value is false.


Boolean[] dpBooleans = new Boolean[9];
System.out.println(dpBooleans[6]);
 Results: null
 This is also easy to understand. Here, only space is applied, but there are no objects in the space! 
 It can be passed through new Complete instantiating the object in the way of 
for (int i = 0; i < 9; i++) {
 dp[i] = new Boolean("false");
}

4. Of course, Boolean can also be directly assigned to true or false


Boolean dp1 = true;
System.out.println(dp1);
 Results: true

Also note the difference between Boolean and boolean:

boolean is the basic data type

Boolean is its encapsulation class, and other classes like 1, have attributes and methods, can new!


Boolean flag = new Boolean("true"); // boolean  You can't! 

Boolean is boolean instantiation object class, and Integer corresponding to int1 like!

Java initializes a Boolean array to false

1. Initialize by default with boolean []


boolean[] boolArray=new boolean[arraySize];

Initialized with new boolean [], with a default value of false.

2. Initialize the array with the fill method under the Arrays class


import java.util.Arrays; 
Boolean boolArray=new Boolean[arraySize];
Arrays.fill(boolArray,Boolean.FALSE);
Arrays. fill () Method:

Arrays. fill (value1, value2) accepts two parameters, value1 is the array variable, and value2 is the value assigned to each variable in the array;

Arrays. fill (value1, m, n, value2) accepts four parameters, and value1 and value2 are the same as above.

Indicates that the array value in the array value1 from the subscript m to the end of n (including m but not n, open before and closed after) is assigned to value2.


Related articles: