Java

Conditional Statements

Make decisions in your code! Learn how to use if, else-if, else, and switch statements.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Make decisions in your code! Learn how to use if, else-if, else, and switch statements. This hands-on tutorial focuses on practical implementation of conditional statements concepts.

Conditional Statements

Conditional statements let your program make decisions based on changing data.

1. if Statement

Use if to specify a block of code to be executed, if a specified condition is true.

if (condition) {
  // block of code to be executed if the condition is true
}

2. else Statement

Use else to specify a block of code to be executed, if the same condition is false.

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}

3. else if Statement

Use else if to specify a new condition to test, if the first condition is false.

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

4. switch Statement

Use switch to select one of many code blocks to be executed. It's often cleaner than many else if statements.

int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  // ...
  default:
    System.out.println("Looking forward to the Weekend");
}

[!WARNING] Don't forget the break keyword! Without it, execution will "fall through" to the next case.

5. Switch Expressions (Java 14+)

A modern, cleaner way to write switch statements. It uses -> and doesn't require break.

int day = 4;
String dayName = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    case 3 -> "Wednesday";
    case 4 -> "Thursday";
    case 5 -> "Friday";
    default -> "Weekend";
};
System.out.println(dayName);

Interactive Code

Try changing the score to see different grades!

JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Java conditional statements: if, else, switch"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

Which keyword is used to stop the execution of more code in a switch case?

stop
break
return
exit

Next Steps

Decisions are great, but what if we need to do something multiple times? Enter Loops.