Conditional Statements in Java: if, else-if, Nested if, switch and Ternary
-
Last Updated: October 7, 2023
-
By: javahandson
-
Series
Learn Java in a easy way
Conditional statements in Java let your program make decisions and pick one path over another. This beginner-friendly guide covers if, if-else, the else-if ladder, nested if, boolean conditions, the ternary shorthand, common mistakes, and interview questions with clear examples.
Every program makes decisions. Should it show a welcome screen or a login form? Is the user old enough? Did the payment go through? To answer questions like these, your code needs a way to choose one path over another.
That is exactly the job of if else statements in Java. They let your program check a condition and then pick what to do next. If the condition holds, run one block. If not, run another. Simple as that.
Think about how you decide things in real life. If it rains, you grab an umbrella. If the light turns red, you stop. Your code works the same way. It looks at a fact, then it acts.
These statements sit at the heart of almost every program you will ever write. Loops use them. Menus use them. Games, banking apps, and websites all lean on them. Master this one topic, and a huge part of Java suddenly clicks into place.
We will start with the plain if statement, then build up through the other conditional statements in Java, step by step. Here is the plan:
You do not need any prior knowledge of control flow. If you can write a basic Java class with a main method, you are ready. We will keep every example short and run through the output together.
[IMAGE PLACEHOLDER: a simple flowchart showing a diamond “condition?” splitting into a “true” branch and a “false” branch. Alt text: “if else statements in java flowchart”]
The if statement is the simplest decision in Java. It says one thing: when this condition holds true, run this block of code. When the condition turns out false, skip the block entirely.
An if statement has two parts. First comes the condition inside the parentheses. Then comes the block inside the curly braces. The condition must be a boolean, meaning it works out to either true or false.
if (condition) {
// this code runs only when the condition is true
}When Java reaches this line, it checks the condition. A true result opens the door, and the block runs. A false result keeps the door shut, and Java jumps straight past the block.
The condition can be anything that yields a boolean. A comparison like age >= 18 works. So does a boolean variable, or a call to a method that returns true or false.
Here is a small rule that trips up beginners. If your block holds just one statement, the curly braces are optional. Java will still attach that single line to the if.
if (score > 50)
System.out.println("You passed");That works fine. But the moment you have two or more statements, you must wrap them in braces. Without braces, only the first line belongs to the if. The rest run no matter what.
My advice? Always use braces, even for one line. They cost you two characters and save you hours of confusion. A stray edit later can quietly break code that has no braces.
Let us write something real. We want to print a message only when a number divides evenly by two. The modulo operator % gives the remainder, so a remainder of zero means the number is an even number.
public class Test {
public static void main(String[] args) {
int number = 8;
if (number % 2 == 0) {
System.out.println(number + " is an even number");
System.out.println(number + " divides by 2");
}
}
}
// Output:
// 8 is an even number
// 8 divides by 2Notice how both lines printed. The condition 8 % 2 == 0 came out true, so Java ran the whole block. Change the number to 7, and nothing prints at all. The condition fails, and the block gets skipped.
The plain if handles one path. But real choices usually have two sides. You want to do one thing when the condition holds, and something different when it does not. That is where if-else steps in.
An if-else statement gives your program a fork in the road. Java tests the condition once. A true result runs the if block. A false result runs the else block instead. Exactly one of the two always runs, never both.
if (condition) {
// runs when the condition is true
}
else {
// runs when the condition is false
}The else block has no condition of its own. It simply catches every case the if did not. Think of it as the default, the fallback for when nothing above it matched.
Our earlier example printed nothing for odd numbers. That feels incomplete. With if-else, we can report both cases clearly.
public class Test {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is an even number");
}
else {
System.out.println(number + " is an odd number");
}
}
}
// Output:
// 7 is an odd numberBecause 7 leaves a remainder of one, the condition fails. So Java skips the if block and runs the else block. Swap in an even value like 8, and the if block wins instead. Either way, the program always says something.
You can drop the braces here too when each block holds one line. Many tutorials show this compact style, so you should know how to read it.
if (number % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");This reads cleanly for a tiny check. Still, the same warning applies. Add a second line to either branch without braces, and the logic quietly breaks. Braces keep you safe as the code grows.
Two paths cover many cases, but not all. Sometimes you face three, four, or more choices. Grading a score, sorting a temperature, routing a menu pick. For these, you chain conditions with else-if.
An else-if ladder stacks several conditions one after another. Java checks them from top to bottom. The first true condition wins, and its block runs. The final else, which is optional, catches anything left over.
if (condition1) {
// runs if condition1 is true
}
else if (condition2) {
// runs if condition1 was false but condition2 is true
}
else if (condition3) {
// runs if only condition3 is true
}
else {
// runs if none of the above matched
}Read it like a checklist. Java tries the first condition. If that fails, it moves to the next. It keeps going until one matches or it runs out of options.
Here is the key rule of the ladder. Only one block ever runs, and it is the first one that matches. Once Java finds a true condition, it runs that block and skips the whole rest of the ladder.
This matters when conditions overlap. Say a number satisfies two of them. The higher one in the ladder still wins, and the lower one never gets a look. Order your conditions with that in mind.
Grading is the classic ladder problem. A score maps to a letter grade, and the ranges never overlap once you order them well.
public class Test {
public static void main(String[] args) {
int score = 82;
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: F");
}
}
}
// Output:
// Grade: BWalk through it. Our score is 82. That first check, score >= 90, fails. Next comes score >= 80, which passes, so Java prints “Grade: B” and stops. It never even looks at the C or F branches.
See why order matters? We test the highest range first and work down. Flip the order, and every score above 70 would grab the C branch by mistake. The ladder rewards careful sequencing.
So far our conditions have been flat. But you can also place one if inside another. We call this a nested if, and it lets you check a second question only after the first one passes.
Nesting means putting an if block inside another if block. The inner check runs only when the outer condition holds true. If the outer condition fails, Java never reaches the inner one at all.
if (condition1) {
if (condition2) {
// runs only when BOTH conditions are true
}
}Picture a locked door behind another locked door. You open the first before you can even try the second. The outer if is the first lock, and the inner if is the second.
Suppose we want numbers that divide by both 2 and 5. One if checks the first rule, and a nested if checks the second.
public class Test {
public static void main(String[] args) {
int number = 20;
if (number % 2 == 0) {
if (number % 5 == 0) {
System.out.println(number + " divides by both 2 and 5");
}
}
}
}
// Output:
// 20 divides by both 2 and 5The number 20 clears the outer check, since it divides by 2. Then it clears the inner check too, since it divides by 5. Both locks open, so the message prints.
Nesting has a downside. Stack too many levels, and your code drifts to the right and grows hard to read. Programmers call this the arrow anti-pattern, because the indentation forms an arrow shape.
Often you can flatten it. When two conditions must both hold, join them with the && operator instead of nesting. The example above becomes one clean line.
if (number % 2 == 0 && number % 5 == 0) {
System.out.println(number + " divides by both 2 and 5");
}Same result, far cleaner. Reach for nesting only when the inner logic truly depends on the outer step. Otherwise, combine your conditions and keep the code flat.
An if is only as good as its condition. So let us slow down and look at what goes inside those parentheses. A condition is any expression that boils down to true or false.
Most conditions compare two values. Java gives you a small set of comparison operators for the job. Each one returns a boolean, which is exactly what an if needs.
== checks whether two values are equal!= checks whether they differ> and < check greater than and less than>= and <= add the “or equal to” caseOne warning stands out. Use == to compare, never a single =. A single equals sign assigns a value, and mixing them up is a classic bug. We will revisit this in the pitfalls section.
Real checks often bundle several facts together. Java offers logical operators to glue conditions into one. They let a single if ask a richer question.
&& is logical AND. It is true only when both sides are true.|| is logical OR. It is true when at least one side is true.! is logical NOT. It flips true to false and back.int age = 25;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
System.out.println("Welcome to the show");
}
// Output:
// Welcome to the showHere both facts must hold. The visitor is old enough, and the visitor owns a ticket. Only then does the welcome print. Swap in ||, and just one of the two would be enough.
One more handy detail. Java uses short-circuit evaluation. With &&, if the left side is false, it never bothers checking the right. That saves work and helps you guard against errors like a null value.
What if you match one variable against many fixed values? A long else-if ladder works, yet it turns noisy fast. The switch statement handles this exact case with flatter, cleaner code.
A switch takes one value and compares it against a list of case labels. When a case matches, its block runs. The break keyword then jumps out, so the next case stays untouched.
switch (value) {
case A:
// runs when value equals A
break;
case B:
// runs when value equals B
break;
default:
// runs when nothing above matched
}The default label is your catch-all. It runs when no case matches, much like the else in a ladder. You may place it anywhere, though the end reads most naturally.
One limit is worth knowing. A switch only tests plain equality against fixed values. It works with int, char, String, and enum types, but not with ranges like score >= 90. For ranges, stick with an else-if ladder.
Say a number stands for a weekday. A switch maps each number to a name in one clean sweep.
int day = 3;
String name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
case 3:
name = "Wednesday";
break;
default:
name = "Another day";
}
System.out.println(name); // Output: WednesdayThe value 3 matches the third case, so name becomes “Wednesday”. The break then ends the switch. Swap in a 9, and the default catches it with “Another day”.
Miss a break, and Java keeps running into the next case. We call this fall-through. Now and then you want it, but usually it hides a bug.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday"); // match starts here
case 3:
System.out.println("Wednesday"); // no break, so this runs too
default:
System.out.println("Another day");
}
// Output:
// Tuesday
// Wednesday
// Another daySee the mess? Three lines printed when we wanted one. The match began at case 2, then ran straight through the rest because no break stopped it.
Modern Java offers a cleaner form. The arrow syntax, added in Java 14, drops the break entirely and never falls through. It reads well and rules out this whole class of bug.
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Another day";
};
System.out.println(name); // Output: WednesdayEach arrow handles one case and nothing else. No break, no fall-through, no stray bugs. When your Java version supports it, the arrow form makes the safer default.
The if-else family is not your only option for decisions. Java also offers switch and the ternary operator. Each fits a different job, so let us line them up.
Which tool you pick depends on the shape of your decision. This table sums up when each one shines.
| Tool | Best For | Watch Out |
|---|---|---|
if-else |
Ranges, complex or combined conditions | Long ladders get hard to scan |
switch |
One variable matched against many fixed values | Works on a limited set of types only |
ternary |
A short two-way choice that yields a value | Nesting it hurts readability fast |
The rule of thumb is easy. Use if-else when your conditions involve ranges or logic like &&. Pick switch when you match one value against a list of fixed options. Save the ternary for a quick either-or that produces a value.
The ternary operator is a compact if-else that returns a value. It uses a question mark and a colon. Read it as: condition ? valueIfTrue : valueIfFalse.
int number = 7; String result = (number % 2 == 0) ? "Even" : "Odd"; System.out.println(result); // Output: Odd
The same logic in if-else would take five or six lines. The ternary folds it into one. Just keep it simple. Once you start nesting ternaries, a plain if-else reads far better.
Decision logic is simple in theory, yet a few traps catch nearly every beginner. Learn to spot these four, and you will save yourself many puzzling bugs.
The most famous trap is writing = when you mean ==. One equals sign assigns a value. Two equals signs compare values. The condition needs the comparison.
int x = 5;
// Wrong: this tries to assign, not compare
// if (x = 10) { ... } // compile error for int
// Right: this compares
if (x == 10) {
System.out.println("x is ten");
}With integers, Java saves you here. It rejects the assignment because an int is not a boolean. But with a boolean variable, both forms compile, and the bug slips through silently. So stay alert.
This one bites almost everyone. For text, == does not compare the letters. It checks whether two variables point to the very same object in memory. That is rarely what you want.
String a = new String("hi");
String b = new String("hi");
if (a == b) { // false, different objects
System.out.println("same object");
}
if (a.equals(b)) { // true, same characters
System.out.println("same text");
}
// Output:
// same textAlways use .equals() to compare the contents of two strings. Keep == for numbers and boolean values. This single habit prevents a whole family of frustrating bugs.
Watch for a semicolon right after the if condition. It ends the statement early, so the block below no longer belongs to the if. The block then runs every time.
int x = 3;
if (x > 10); // <-- stray semicolon, the if now does nothing
{
System.out.println("This prints no matter what");
}
// Output:
// This prints no matter whatYour compiler will not flag this. The code runs, just not the way you meant. When an if seems to ignore its condition, hunt for a rogue semicolon first.
In an else-if ladder, order decides everything. Put a broad condition too high, and it swallows cases meant for the ones below it. Those lower branches then become dead code.
Say you check score >= 70 before score >= 90. Every high score grabs the 70 branch first, so the 90 branch never fires. Always test the tightest, highest range first, then widen as you go down.
Let us tie it all together in one small program. We will build a simple ticket checker for a movie. It uses an if-else ladder, combined conditions, and a clear default.
The checker looks at a viewer’s age and decides which show they may watch. It sorts them into three buckets, then handles the leftover case with an else.
public class TicketChecker {
public static void main(String[] args) {
int age = 15;
boolean withGuardian = true;
if (age >= 18) {
System.out.println("Any movie is fine");
}
else if (age >= 13 && withGuardian) {
System.out.println("PG-13 movies are allowed with a guardian");
}
else if (age >= 13) {
System.out.println("PG-13 movies are allowed, ask at the desk");
}
else {
System.out.println("Only family movies for now");
}
}
}
// Output:
// PG-13 movies are allowed with a guardianEvery branch here earns its place. The first one handles adults. Two middle branches split teenagers by whether a guardian tags along. A final else catches younger viewers with a friendly default.
Trace the logic with our values. The age is 15, so the first check, age >= 18, fails. Java moves to the second branch.
There it tests age >= 13 && withGuardian. The viewer is 15 and has a guardian, so both parts hold. That branch prints, and the ladder stops right there.
Try changing the values yourself. Set the age to 20, and the very first branch wins. Set it to 10, and only the else runs. Playing with inputs is the fastest way to make this stick.
A: A plain if runs its block only when the condition is true, and it does nothing when the condition is false. An if-else adds a second block that runs when the condition is false. So if handles one path, while if-else always takes one of two paths.
A: Yes, but only for a single statement. Without braces, just the one line right after the if belongs to it. The moment you need two or more statements, you must add braces, or the extra lines run outside the if.
A: Java checks the conditions from top to bottom and runs the first one that turns out true. It then skips every remaining branch. If no condition matches, the final else block runs, and that else is optional.
A: A nested if is an if placed inside another if. The inner condition matters only when the outer condition holds true. It suits cases where a second check depends on the first, though you can often replace it with the && operator.
A: The == operator compares references, so it checks whether two variables point to the same object. Two strings with identical text can still live in different objects, so == returns false. The .equals() method compares the actual characters, which is what you usually want.
A: Reach for switch when you match a single variable against many fixed values, such as a day number or a menu choice. Use if-else when your conditions involve ranges, combined logic, or anything beyond simple equality.
A: The ternary operator is a compact if-else that returns a value, written as condition ? valueIfTrue : valueIfFalse. It fits a short two-way choice on one line. For anything longer or nested, a full if-else reads much better.
A: An if condition in Java must evaluate to a boolean, meaning true or false. Unlike some languages, Java does not treat numbers or objects as truthy or falsy. A condition like if(1) will not compile.
A: That semicolon ends the if as an empty statement. The block below it then no longer belongs to the if, so it runs every time regardless of the condition. The code still compiles, which makes this a sneaky bug to spot.
A: Yes, order is critical. Since Java runs the first matching branch, a broad condition placed too high can swallow cases meant for lower branches. Put the tightest, most specific condition first and widen as you move down.
Let us wrap up what we covered about conditional statements in Java. An if statement runs a block when its condition holds true, and it skips the block otherwise.
An if-else adds a second path for the false case, so your program always does something. When you have many paths, the else-if ladder checks conditions in order and runs the first match.
Nested if lets one check sit inside another, though the && operator often flattens it into cleaner code. For matching one value against many fixed options, the switch statement keeps the code tidy. Good conditions rely on comparison operators like == and logical operators like && and ||.
Watch the classic traps: a single =, comparing strings with ==, and stray semicolons. Practice with small programs like the ticket checker, and these decisions will soon feel like second nature.