Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
A condition switches the track: exactly one branch runs. Eight small programs cover if and else, why braces matter, the dangling else, nested ifs, else-if ladders, the arrow switch, fall-through and yield.
What you will learn
- Choose between two paths with if and else
- Avoid the missing-brace and dangling-else traps
- Order an else-if ladder so the first true check is the right one
- Use the arrow switch, switch expressions and yield, and recognise old-style fall-through
Before you start
- Java operators and expressions
Every language needs a way to make decisions, and in Java you do it with if or switch. Picture a train reaching a set of points. The points ask one question, say "is age 18 or more?". Jack is 20, so the answer is true and he takes the top track: allow entry. Priya is 16, so she takes the bottom track: ask for an ID. One condition, two tracks, and only one of them is used.
if and else
package org.studyeasy.s02l09;
public class Ex01_IfElse {
public static void main(String[] args) {
boolean isLoggedIn = true;
int age = 16;
if (isLoggedIn) {
System.out.println("Dashboard for Emma");
}
if (age >= 18) {
System.out.println("Entry allowed");
} else {
System.out.println("Show your ID");
}
}
}
Dashboard for Emma
Show your ID
An if on its own only handles the true case. If the user isn't logged in, nothing happens and nobody is told. Add else for the false case. With if and else, exactly one block runs, never both.
Braces decide what belongs to the if
In Java, indentation doesn't decide anything. Braces do.
int balance = 500;
if (balance < 100)
System.out.println("Low balance");
System.out.println("Fee charged");
Fee charged
Without braces, the if owns only the next line. The fee line looks like part of it, but it always runs, so the customer is charged although the balance is fine.
The dangling else
int age = 20;
boolean hasTicket = false;
if (age >= 18)
if (hasTicket)
System.out.println("Enjoy the show");
else
System.out.println("Too young");
Too young
An else joins the nearest if, which here is hasTicket, not the age check. So a 20-year-old is told "Too young". Always write braces, even around a single line, and there's no doubt where an if starts and ends.
A decision inside a decision
package org.studyeasy.s02l09;
public class Ex04_NestedIf {
public static void main(String[] args) {
boolean isRegistered = true;
String password = "java25";
String input = "java25";
if (isRegistered) {
if (input.equals(password)) {
System.out.println("Welcome back, Priya");
} else {
System.out.println("Wrong password");
}
} else {
System.out.println("Please sign up");
}
}
}
Welcome back, Priya
The password is only checked for registered users. Compare text with .equals, which compares the letters, not ==. (A real program would never keep a password in the code; it just keeps the example short.)
The else-if ladder: the first true check wins
package org.studyeasy.s02l09;
public class Ex05_Ladder {
public static void main(String[] args) {
int score = 85;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}
System.out.println("Lucas got " + grade);
}
}
Lucas got B
Java checks from the top. score >= 90 is false; score >= 80 is true, so the grade is B and the rest is skipped, even though 85 is also at least 70. Move the >= 70 check to the top and Lucas gets a C. Put the strictest check first.
The modern switch
When you match one value against many options, a switch reads better than a long ladder.
package org.studyeasy.s02l09;
public class Ex06_ModernSwitch {
public static void main(String[] args) {
String day = "SAT";
switch (day) {
case "MON" -> System.out.println("Shop opens late");
case "SAT", "SUN" -> System.out.println("Weekend: rest");
default -> System.out.println("Workday");
}
String type = switch (day) {
case "SAT", "SUN" -> "Weekend";
case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday";
default -> "Unknown";
};
System.out.println(type);
}
}
Weekend: rest
Weekend
- You can switch on a String. One case can list several values:
"SAT", "SUN". - The arrow form needs no
break. - The second switch is an expression: it returns a value into
type. Note the semicolon after its closing brace. A switch expression must cover every possibility; deletedefaultandjavacsays it doesn't cover all values.
Old style: without break, cases fall through
int day = 2;
switch (day) {
case 1:
System.out.println("Mon");
case 2:
System.out.println("Tue");
case 3:
System.out.println("Wed");
default:
System.out.println("Other");
}
Tue
Wed
Other
You'll see the colon form in a lot of existing code. Java lands on case 2, prints Tue, and keeps going through every line below. That's fall-through, the classic switch bug. Add break; after each case, or use the arrow form, which never falls through.
A block that yields a value
package org.studyeasy.s02l09;
public class Ex08_Yield {
public static void main(String[] args) {
int month = 2;
int days = switch (month) {
case 2 -> {
System.out.println("Checking Feb");
yield 28;
}
case 4, 6, 9, 11 -> 30;
default -> 31;
};
System.out.println(days);
}
}
Checking Feb
28
When a case needs more than one line, give it a block in braces and hand the answer back with yield. The one-line cases return 30 or 31 directly.
Recap
| Tool | Remember |
|---|---|
if / else | Exactly one block runs |
| Braces | Always write them; an else joins the nearest if |
| Text comparison | .equals, not == |
| else-if ladder | First true check wins; strictest on top |
| Arrow switch | Several labels per case, no fall-through |
| Switch expression | Returns a value, needs default, ends with ; |
yield | Hands back a value from a multi-line case |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.
Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.
Java Hello World with Maven: What the JDK Does and What Maven Adds
javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.
Java Variables, Keywords and Naming Rules
A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.
