Java If...Else & Switch

Make decisions.

✍️ 2 exercises in this lesson
  • if (condition) { } else if (other) { } else { }
  • Ternary: String r = age >= 18 ? "Adult" : "Minor";
  • switch: compare one value with many cases. Modern Java (14+) supports the arrow form, which needs no break and can return a value.

Key Takeaways: Java If...Else & Switch

Mastering Java If...Else & Switch helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java If...Else & Switch Code Example

Java
public class Main {
    public static void main(String[] args) {
        int marks = 82;

        if (marks >= 85) {
            System.out.println("Grade A");
        } else if (marks >= 70) {
            System.out.println("Grade B");
        } else {
            System.out.println("Grade C");
        }

        int day = 5;
        String name = switch (day) {
            case 1, 7 -> "Weekend";
            case 5 -> "Friday";
            default -> "Weekday";
        };
        System.out.println(name);
        System.out.println(marks >= 50 ? "Pass" : "Fail");
    }
}
Output
Grade B
Friday
Pass
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java If...Else & Switch Practice Exercises

Check what you learned in “Java If...Else & Switch”.

/ 2 solved
Fill in the blank

Modern switch uses arrows.

String name = switch (day) { case 1  "Mon"; default -> "Other"; };
✓ Correct! Not quite. Try again.
Multiple choice

Which operator is the ternary operator?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services