Java Boolean type

We’ll cover the following

  • Booleans
  • Note
  • Example

Booleans

Java has a simple type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, such
as a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for.

Booleans are used to perform logical operations, most commonly to determine whether some condition is true. For example:

boolean enrolled = true; 

boolean credited = false;

Here a variable named enrolled of type boolean is declared and initialized to a value of true, and another boolean named credited is declared and initialized to false.

Note

In some languages, such as C or C++, integer values can be treated as Booleans, with 0 equal to false and any other value equal to true. In Java, you can’t convert between an integer type and a boolean type.

Example

Here is a program that demonstrates the boolean type:

// Demonstrate boolean values

package JAVA.Basic;

public class BoolTest {
    public static void main(String[] args) {
        boolean b;
        b = false;
        System.out.println("b is " + b);
        b = true;
        System.out.println("b is " + b);
        // a boolean value can control the if statement
        if (b)
            System.out.println("This is executed.");
        b = false;
        if (b)
            System.out.println("This is not executed.");
        // outcome of a relational operator is a boolean value
        System.out.println("10 > 9 is " + (10 > 9));
    }
}

The output generated by this program is shown here:

There are three interesting things to notice about this program. First, as you can see,
when a boolean value is output by println( ), “true” or “false” is displayed. Second,
the value of a boolean variable is sufficient, by itself, to control the if statement. There
is no need to write an if statement like this:

if(b == true) …


Third, the outcome of a relational operator, such as <, is a boolean value. This is why the expression 10 > 9 displays the value “true.” Further, the extra set of parentheses
around 10 > 9 is necessary because the + operator has a higher precedence than the >.

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Java char type


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , Swiggy


One comment

Leave a Reply

Your email address will not be published.