In Java, boolean literals are values that can be assigned to boolean variables or used in boolean expressions. There are two boolean literals in Java: true and false.
Boolean literals are commonly used in control statements such as if, while, and for to control the flow of execution of a program. They can also be used in expressions and conditions.
Here is an example of how to use boolean literals in a Java program:
boolean flag = true;
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");
}
int x = 10;
int y = 20;
boolean result = x > y; // result is falseSource:www.lautturi.comIn the first example, the if statement executes one of the two blocks of code depending on the value of the flag variable. In the second example, the boolean expression x > y evaluates to false and is assigned to the result variable.
Boolean literals can also be used as arguments to methods or constructors that take boolean values as parameters. For example:
public void setFlag(boolean flag) {
this.flag = flag;
}
// Example usage
MyClass obj = new MyClass();
obj.setFlag(true);
In this example, the setFlag() method takes a boolean value as a parameter and sets it to a class variable. The true boolean literal is passed as an argument to the setFlag() method.