← Back to Core Java Course | Chapter 4: Control Flow | Lesson 1 of 9

Java if Statement

Basic if Statement

An if statement evaluates its parenthesized boolean condition once; if it's true, the block that follows executes, and if it's false, Java skips straight past that block to whatever code comes next.

Example: Basic if Statement

java
public class Main {
	public static void main(String[] args) {
		int age = 20;
		if (age >= 18) {
			System.out.println("Condition was true - block executed");
		}
	}
}

Comparisons inside if Conditions

Double equals (==) inside a condition checks whether two primitive values match exactly -- a very common beginner mistake is writing a single = here, which is assignment, not comparison, and usually causes a compiler error for boolean contexts.

Example: Comparisons inside if Conditions

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		if (x == 5) { // == is comparison; a single '=' here would be a compile error
			System.out.println("x equals 5");
		}
	}
}

Logical AND (&&) inside if

Chaining conditions with && inside one if means every single one must evaluate to true for the block to execute -- if any single condition is false, the whole check short-circuits to false immediately.

Example: Logical AND (&&) inside if

java
public class Main {
	public static void main(String[] args) {
		int age = 25;
		boolean hasId = true;
		if (age >= 18 && hasId) { // both must be true
			System.out.println("Entry allowed");
		}
	}
}

Logical OR (||) inside if

Using || instead lets the block run if just one of several conditions holds, which is the right choice when you want to react to any one of multiple acceptable situations.

Example: Logical OR (||) inside if

java
public class Main {
	public static void main(String[] args) {
		boolean isAdmin = false;
		boolean isOwner = true;
		if (isAdmin || isOwner) { // runs if just one holds
			System.out.println("Access granted");
		}
	}
}

Nested if Statements

Placing an if statement inside another if's block lets you ask a second, more specific question only once the first, broader condition has already been confirmed true -- useful for drilling down through layered eligibility checks.

Example: Nested if Statements

java
public class Main {
	public static void main(String[] args) {
		int age = 20;
		boolean hasLicense = true;
		if (age >= 18) {
			if (hasLicense) { // more specific question, asked only after the first passes
				System.out.println("Can drive");
			}
		}
	}
}

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.