Java Fundamentals  «Prev 

Java Boolean Datatype

The boolean[1] data type requires 1 bit of memory and is used to store values with one of two possible states: true or false.
You can think of the boolean type as a 1-bit integer type that can have only two possible values, 0 or 1.
However, boolean data cannot be used as numbers. You set a boolean variable by using the true and false keywords, which are the only legal boolean values.

boolean Type

The boolean type represents truth values. This type has only two possible values, representing the two Boolean states:
  1. on or off,
  2. yes or no,
  3. true or false.
Java reserves the words true and false to represent these two Boolean values. Programmers coming to Java from other languages should note that Java is much stricter about its Boolean values than other languages. In particular, a boolean is neither an integral nor an object type, and incompatible values cannot be used in place of a boolean. In other words, you cannot take shortcuts such as the following in Java:

Object o = new Object();
int i = 1; // primitive integer
if (o) { // top level reference object not boolean
 while(i) {
 //...
 }
}

Instead, Java forces you to write cleaner code by explicitly stating the comparisons you want:
if (o != null) {
 while(i != 0) {
  // ...
 }
}

Java Reference

Category: Boolean

The Boolean category has only one data type: boolean. A boolean variable can store one of two values: true or false. It is used in scenarios where only two states can exist.
See table 6.5 for a list of questions and their probable answers.

Question Probable answers
Did you purchase the exam voucher? Yes/No
Did you log in to your email account? Yes/No
Is Bernie Sanders a communist? Yes/No

Table 6.5 shows suitable data that can be stored using a boolean data type

Note: In the Java exam, the questions test your ability to select the best suitable data type for a condition that can only have two states:
yes/no or true/false. The correct answer here is the boolean type. Here is code defining boolean primitive variables:
boolean voucherPurchased = true;
boolean examPrepStarted = false;
[1] boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.