Today you will learn:
if, else if, and elseswitch statementsBy the end, you will be able to control the flow of your programs based on conditions.
Conditions allow your program to make decisions.
int score = 85;
if(score >= 90) {
System.out.println("A");
} else if(score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}
Explanation:
if → first conditionelse if → additional conditionselse → runs if no condition is trueYou can place conditions inside other conditions.
int age = 20;
boolean hasTicket = true;
if (age >= 18) {
if (hasTicket) {
System.out.println("You may enter");
} else {
System.out.println("You need a ticket");
}
}
Explanation:
The switch statement is used when you have many specific cases.
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;
default:
System.out.println("Invalid day");
}
Explanation:
case → possible valuesbreak → stops executiondefault → runs if no case matches
int score = 85;
if(score >= 90) {
System.out.println("A");
} else if(score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}
Create a program that assigns a grade to a student based on their score.
Steps:
if and else if to assign gradesExample:
public class Grade {
public static void main(String[] args) {
int score = 75;
if(score >= 90) {
System.out.println("Grade A");
} else if(score >= 80) {
System.out.println("Grade B");
} else if(score >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
}
}