In programming, there’s frequently a requirement for a data type offering only two potential values, like
Java furnishes a boolean data type specifically designed for this purpose, enabling storage of either true or false values.
Defined with the boolean keyword, a boolean type is limited to containing either the value true or false.
|
Yet, it's typical to yield boolean values from boolean expressions, primarily for conditional evaluation, as illustrated below.
A boolean expression yields either a true or false boolean value.
This functionality is beneficial for constructing logical operations and obtaining answers.
For instance, employing a comparison operator like the greater than (>) operator enables you to ascertain whether an expression or a variable evaluates to true or false.
|
Alternatively, it's even simpler.
|
In the following examples, we utilize the equal to (==) operator to assess an expression.
|
|
Consider a “real-life scenario” where we need to determine if an individual is eligible to vote.
In the following example, we utilize the >= comparison operator to ascertain if the age (25) surpasses or equals the minimum voting age limit, set at 18.
|
Isn’t that neat? An even more efficient approach (given our momentum) would be to encapsulate the aforementioned code within an if…else statement, allowing us to execute different actions based on the outcome.
If myAge is greater than or equal to 18, print “Old enough to vote!”. Otherwise, print “Not old enough to vote.”.
|
Booleans serve as the foundation for all Java comparisons and conditions, with further exploration into conditions (if…else) slated for the next chapter. |