In Java, a boolean is a primitive data type that represents a true or false value. It is used to represent a binary choice or a logical condition in a program.
To declare a boolean variable in Java, you can use the boolean
keyword followed by the variable name. For example:
boolean flag = true;Source:www.lautturi.com
Here, flag
is a boolean variable that is initialized to true
.
Boolean variables can be assigned a value using the boolean literals true
and false
. For example:
boolean flag1 = true; boolean flag2 = false;
You can also use boolean variables 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 variables 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.
Boolean variables can be used as the return type of 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.