boolean
Java has a boolean type for logical values. It can have only one of two possible values, true or false.
This is the type returned by all relational operators.
Here is a program that demonstrates the boolean type:
public class Main {
public static void main(String args[]) {
boolean boolVariable;
boolVariable = false;
System.out.println("b is " + boolVariable);
boolVariable = true;
System.out.println("b is " + boolVariable);
if (boolVariable) {
System.out.println("This is executed.");
}
boolVariable = false;
if (boolVariable) {
System.out.println("This is not executed.");
}
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output:
b is false
b is true
This is executed.
10 > 9 is true
Boolean Literals
Boolean literals are only two logical values: true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean.
public class Main {
public static void main(String[] argv) {
boolean b = true;
int i = b;
}
}
If you try to compile the program, the following error message will be generated by compiler.
Main.java:5: incompatible types
found : boolean
required: int
int i = b;
^
1 error