Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

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.

A condition age >= 18 splits the track. Jack, 20, gets true and goes to Entry allowed. Priya, 16, gets false and goes to Show your ID. Exactly one branch runs. age >= 18 ? Entry allowed Show your ID true false Jack 20, Priya 16
if and else: one condition picks exactly one track.

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; delete default and javac says 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

ToolRemember
if / elseExactly one block runs
BracesAlways write them; an else joins the nearest if
Text comparison.equals, not ==
else-if ladderFirst true check wins; strictest on top
Arrow switchSeveral labels per case, no fall-through
Switch expressionReturns a value, needs default, ends with ;
yieldHands back a value from a multi-line case

Keep going in Java · 11 of 79

Previous
Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
Next post
Java Loops: for, while, do-while and for-each
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • if and else
  • Braces decide what belongs to the if
  • The dangling else
  • A decision inside a decision
  • The else-if ladder: the first true check wins
  • The modern switch
  • Old style: without break, cases fall through
  • A block that yields a value
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.