boolean
- Java course
- Beginner
- Lesson 8/116
- 3 min
Learn true/false values with boolean.
What is boolean?
boolean is a type that can take only two values: true and false. It is used for logical decisions and flags.
boolean active = true;
boolean ready = false;A boolean variable usually holds the result of a condition. For example userInput > 0 produces true or false.
Boolean values are written without quotes. "true" is a String, while true is a boolean.
Practice Define a boolean and print it
Write a Main class with a main method. Assign true to boolean active. Print it with println.
Sample solution
public class Main {
public static void main(String[] args) {
boolean active = true;
System.out.println(active);
}
}Expected output
true
What is boolean used for?
Boolean variables are usually flags that steer the program flow. They hold whether a feature is on/off, whether a user is signed in, or whether a file exists.
An if condition expects a boolean inside its parentheses:
boolean signedIn = true;
if (signedIn) {
System.out.println("Welcome");
}That is why comparisons (>, ==) produce a boolean.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the boolean concepts
| Term | Meaning |
|---|---|
true |
True |
false |
False |
boolean |
Logical type |
! |
Not |
&& |
And |
2 Which is a valid boolean value?
- 42
- true Correct answer
- "yes"
- 1
Explanation: boolean can only be true or false.
3 Assign a value to a boolean variable
boolean active = ____;
boolean active = true;
Explanation: A boolean is written without quotes as true or false.