Java Tutorial · Control Flow · Lesson 13 of 37
Java If Else
Make decisions with if, else if and else.
if, else if, else
public class Main {
public static void main(String[] args) {
int score = 82;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("Keep practising");
}
}
}
Output
B
Run this on your computer — see “Get Started” for setup.
Conditions must be boolean — unlike some languages, Java won't treat 0 or null as false.
Nested conditions and guard clauses
Return early from methods to avoid deeply nested if statements:
public class Main {
public static void main(String[] args) {
System.out.println(shippingCost(0, false));
System.out.println(shippingCost(120, false));
System.out.println(shippingCost(40, true));
System.out.println(shippingCost(40, false));
}
static String shippingCost(double orderTotal, boolean isMember) {
if (orderTotal <= 0) return "Empty order";
if (orderTotal >= 100 || isMember) return "Free shipping";
return "Shipping: $4.99";
}
}
Output
Empty order Free shipping Free shipping Shipping: $4.99
Run this on your computer — see “Get Started” for setup.
Test yourself
Can you write if (1) { ... } in Java?
YesNo — the condition must be a boolean
Show answer
Answer: No — the condition must be a boolean