Curriculum / Java / Lesson 06

Conditions (if / else) in Java

Java's conditional statements are almost identical to C++'s, requiring a genuine boolean expression inside if.

6 of 11
beginner 📖 5 min read 🎯 1 question

Conditions

Java's conditional statements are almost identical to C++'s, requiring a genuine boolean expression inside if. Java also supports switch, including a modern "arrow" syntax in recent versions.

💡 Key insight Since Java 14, switch expressions can use a cleaner arrow syntax (case X -> ...) that avoids needing 'break' at all.

Syntax

syntax
if (condition) {
    // code
} else if (condition2) {
    // code
} else {
    // code
}

Example

Only the first true branch runs; the rest are skipped, same as C/C++.

java
public class Main {
    public static void main(String[] args) {
        int marks = 72;
        if (marks >= 90) {
            System.out.println("Grade: A");
        } else if (marks >= 60) {
            System.out.println("Grade: B");
        } else {
            System.out.println("Grade: C");
        }
    }
}
outputGrade: B

Try it yourself

Copy this example into the Java compiler and run it — try changing a value and see what happens.

Quick Quiz

1. What should you use to compare the content of two String objects in Java?

Back to curriculum