Summary - Conditionals
- Java course
- Beginner
- Lesson 41/116
- 5 min
Combine if, else if, switch and ternary to write a day-of-week app.
Summary - Conditionals
In this group you learned conditionals:
- if: single condition
- else/else if: alternative branches
- nested if: multiple conditions together
- switch: multi-branch (case/break/default)
- ternary: one-line condition
These structures let the program make decisions. Now combine them and write a day-of-week app.
Practice Day name (switch)
Write a Main class with a main method. Assign 3 to int day. With switch (day) print "Monday" for case 1:, "Tuesday" for case 2:, "Wednesday" for case 3:. Add break; after each case.
Sample solution
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
}
}Expected output
Wednesday
Practice Greeting (if/else if/else)
Write a Main class with a main method. Assign 14 to int hour. With if (hour < 12) print "Good morning", else if (hour < 18) print "Good day", else print "Good evening".
Sample solution
public class Main {
public static void main(String[] args) {
int hour = 14;
if (hour < 12) {
System.out.println("Good morning");
} else if (hour < 18) {
System.out.println("Good day");
} else {
System.out.println("Good evening");
}
}
}Expected output
Good day
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which structure best picks a branch by specific values?
- while
- switch Correct answer
- for
- Scanner
Explanation: switch branches by specific values.
2 Match the conditional structures
| Term | Meaning |
|---|---|
if |
Condition |
switch |
Multi-branch |
? |
Ternary |
else |
Fallback |
3 Complete the ternary
int x = 10;
String s = (x > 0) ? "Positive" : ____;
int x = 10;
String s = (x > 0) ? "Positive" : "Negative";
Explanation: When the condition is false, "Negative" is assigned.