← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 12 of 12

Java Booleans

The boolean type stores one of exactly two values, true or false, and drives the decisions made by every conditional statement and loop in a Java program.

The boolean Type

The boolean type represents exactly one of two possible values, true or false, and is Java's smallest data type conceptually, used whenever a piece of information is a simple yes-or-no or on-or-off flag.

Example: The boolean Type

java
public class Main {
	public static void main(String[] args) {
		boolean isOpen = true; // simple yes/no flag
		System.out.println(isOpen);
	}
}

Boolean Expressions

A boolean expression is any expression that evaluates to true or false, most commonly formed by comparing two values with operators like >, <, ==, or != rather than by writing a literal true or false directly.

Example: Boolean Expressions

java
public class Main {
	public static void main(String[] args) {
		boolean isAdult = 20 > 18; // comparison, not a literal true/false
		System.out.println(isAdult);
	}
}

Booleans in Conditions

Boolean values are what control flow statements like if, while, and for actually test: an if statement runs its block only when the boolean expression inside its parentheses evaluates to true.

Example: Booleans in Conditions

java
public class Main {
	public static void main(String[] args) {
		boolean loggedIn = true;
		if (loggedIn) {
			System.out.println("Runs only because loggedIn is true");
		}
	}
}

Boolean Variables from Comparisons

Storing the result of a comparison in a named boolean variable, rather than repeating the comparison inline, makes conditions easier to read and lets the same computed result be reused in multiple places.

Example: Boolean Variables from Comparisons

java
public class Main {
	public static void main(String[] args) {
		int score = 75;
		boolean passed = score >= 60; // named result, reused below
		System.out.println(passed);
		System.out.println("Result: " + passed);
	}
}

Default Boolean Value

An uninitialized boolean instance or static field automatically defaults to false, and every element of a newly created boolean array also starts out as false until a value is explicitly assigned.

Example: Default Boolean Value

java
public class Main {
	static boolean flag; // uninitialized instance field
	public static void main(String[] args) {
		boolean[] flags = new boolean[3];
		System.out.println(flag);       // defaults to false
		System.out.println(flags[0]);   // array elements default to false too
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.