Java If...Else and Switch
Conditions let your program choose what to do based on a value.
The if Statement
Code inside an if block runs only when the condition is true:
Example
public class Main {
public static void main(String[] args) {
int marks = 75;
if (marks >= 50) {
System.out.println("You passed");
}
}
}You passed
if...else
Add else for what should happen when the condition is false:
Example
int balance = 300;
int price = 450;
if (balance >= price) {
System.out.println("Payment done");
} else {
System.out.println("Not enough balance");
}Not enough balance
else if
Use else if to test several conditions in order. Java runs the first block that is true and skips the rest.
Example
public class Main {
public static void main(String[] args) {
int marks = 68;
if (marks >= 80) {
System.out.println("Grade A");
} else if (marks >= 65) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}Grade B
The Ternary Operator
For a short if...else that gives back a value, use condition ? valueIfTrue : valueIfFalse:
Example
int temperature = 38;
String weather = (temperature > 35) ? "Very hot" : "Pleasant";
System.out.println(weather);Very hot
The switch Statement
switch compares one value against many fixed choices. It is cleaner than a long chain of else if.
Example
public class Main {
public static void main(String[] args) {
int day = 5;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
}
}
}Friday
| Keyword | Purpose |
|---|---|
case | One possible value |
break | Stops the switch so the next cases do not run |
default | Runs when no case matches |
If you forget break, Java "falls through" and runs the next case too. This is a very common bug.
The Arrow switch (Java 14+)
Modern Java has a shorter switch with ->. It never falls through, so you do not need break:
Example
String size = "M";
int price = switch (size) {
case "S" -> 800;
case "M" -> 1000;
case "L", "XL" -> 1200;
default -> 0;
};
System.out.println("Shirt price: Rs " + price);Shirt price: Rs 1000
Exercise
Exercise
What is printed if x is 10? if (x > 10) { print "A" } else if (x == 10) { print "B" } else { print "C" }
