Java boolean data type

Java boolean data type

The boolean data type in Java represents a true or false value. It is a primitive data type that occupies one byte of memory and has a range of true and false.

In Java, you can use the boolean keyword to declare a boolean variable. For example:

boolean flag = true;
‮ecruoS‬:www.lautturi.com

Here, flag is a boolean variable that is initialized to true.

You can also use the boolean data type as a return type for a method or as a parameter type for a method or a constructor. For example:

public boolean isEven(int x) {
    return x % 2 == 0;
}

public void setFlag(boolean flag) {
    this.flag = flag;
}

In the first example, the isEven() method takes an integer as input and returns a boolean value indicating whether the number is even or not. In the second example, the setFlag() method takes a boolean value as a parameter and sets it to a class variable.

Boolean values can be used in control statements such as if, while, and for to control the flow of execution of a program. For example:

if (flag) {
    // execute this block if flag is true
    System.out.println("flag is true");
} else {
    // execute this block if flag is false
    System.out.println("flag is false");
}

In this example, the if statement executes one of the two blocks of code depending on the value of the flag variable.

You can also use boolean values in expressions and conditions. For example:

int x = 10;
int y = 20;
boolean result = x > y; // result is false

In this example, the boolean expression x > y evaluates to false and is assigned to the result variable.

Created Time:2017-11-03 00:14:41  Author:lautturi