Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Java's if-else statement executes one block of code when a condition is true and a different block when it is false. A nested if-else places one if-else inside another, letting you test multiple dependent conditions in sequence — for example, deciding the largest of three numbers or assigning a letter grade. These are part of Java's conditional (decision-making) statements, which control program flow based on Boolean expressions.
Below, we walk through every form of the if statement in Java, then build the headline example — a complete, runnable nested if…else program — followed by more examples, comparisons, best practices, and the mistakes that trip up most beginners.
The if-else statement is one of Java's core conditional (decision-making) statements. It evaluates a Boolean expression — an expression that resolves to either true or false — and runs one of two blocks of code accordingly. If the condition is true, the if block runs; otherwise the else block runs. This is how a Java program chooses different paths at runtime instead of executing every line top to bottom.
The basic syntax looks like this:
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}The condition must evaluate to a boolean. Unlike some languages, Java does not treat numbers or non-null objects as "truthy" — if (1) is a compile error. You must write an explicit comparison such as num > 0 or a boolean variable. This strictness prevents a whole class of bugs.
Java provides four practical forms of the if construct. Knowing which one fits your problem keeps logic readable.
Runs a block only when the condition is true; otherwise nothing happens.
if (age >= 18) {
System.out.println("You are eligible to vote.");
}Provides an alternative path when the condition is false.
if (age >= 18) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible yet.");
}Tests a series of conditions in order and runs the first true block, falling through to a final else if none match. For a dedicated walkthrough of this form, see the nested if-else-if statement program.
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}Places one if-else inside another. The inner condition is evaluated only when the outer condition is true, which is exactly what you need for dependent decisions. This also makes it efficient — an inner check that is irrelevant when the outer condition fails is simply never run, so you avoid needless comparisons (for example, checking donation weight only after confirming the donor meets the minimum age).
if (outerCondition) {
if (innerCondition) {
// runs when both are true
} else {
// runs when outer is true but inner is false
}
} else {
// runs when outer is false
}Here is the headline ask: a complete, runnable Java program that uses a nested if…else to find the largest of three numbers. The inner if-else runs only after the outer condition has narrowed the candidates, which perfectly demonstrates dependent conditions.
public class LargestOfThree {
public static void main(String[] args) {
int a = 25, b = 42, c = 17;
int largest;
if (a > b) {
// a is bigger than b, now compare a with c
if (a > c) {
largest = a;
} else {
largest = c;
}
} else {
// b is bigger than or equal to a, now compare b with c
if (b > c) {
largest = b;
} else {
largest = c;
}
}
System.out.println("The largest number is: " + largest);
}
}For the values above, the output is:
The largest number is: 42Notice how the inner if (a > c) is only reached when the outer if (a > b) is already true. That dependency is the defining trait of a nested if-else. The same pattern scales to grade classification, where you first check the broad band, then refine inside it:
public class GradeClassifier {
public static void main(String[] args) {
int score = 82;
if (score >= 60) {
// student passed, now decide the grade band
if (score >= 90) {
System.out.println("Pass - Grade A");
} else if (score >= 75) {
System.out.println("Pass - Grade B");
} else {
System.out.println("Pass - Grade C");
}
} else {
System.out.println("Fail - Please reattempt");
}
}
}Here the grade band is only evaluated after we confirm the student passed — a natural, real-world nesting of decisions.
Two classic beginner programs show the simple if-else in action. First, checking whether a number is even or odd using the modulo operator:
public class EvenOdd {
public static void main(String[] args) {
int num = 12;
if (num % 2 == 0) {
System.out.println(num + " is an Even Number");
} else {
System.out.println(num + " is an Odd Number");
}
}
}Next, a nested eligibility check that confirms a person is both old enough and a citizen before allowing them to vote — two conditions where the second only matters if the first passes:
public class VotingEligibility {
public static void main(String[] args) {
int age = 20;
boolean isCitizen = true;
if (age >= 18) {
if (isCitizen) {
System.out.println("You can vote.");
} else {
System.out.println("Citizenship required to vote.");
}
} else {
System.out.println("You must be at least 18 to vote.");
}
}
}When you have many discrete options, a switch statement is often cleaner than a long if-else-if ladder. The table below compares the two so you pick the right tool.
In short: use a ladder when conditions are ranges or involve multiple variables; use a switch when you are matching one variable against a fixed list of exact values.
When an if-else simply assigns or returns a value, the ternary operator condenses it into a single expression: condition ? valueIfTrue : valueIfFalse.
int num = 7;
// Full if-else
String result;
if (num % 2 == 0) {
result = "Even";
} else {
result = "Odd";
}
// Equivalent ternary shorthand
String shorthand = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(shorthand); // OddTernaries are great for short assignments, but avoid nesting them deeply — a chain of nested ternaries is far harder to read than an equivalent if-else-if ladder.
String name = "admin";
// Wrong: compares references, can be false
if (name == "admin") { /* unreliable */ }
// Correct: compares the text content
if (name.equals("admin")) {
System.out.println("Welcome, admin!");
}Java's if-else is the foundation of decision-making: it runs one block when a condition is true and another when false. A nested if-else extends that by testing an inner condition only after an outer one passes — perfect for problems like the largest of three numbers or grade classification shown above. Choose a ladder for flat independent choices, a switch for fixed value sets, and the ternary for short value assignments. Add braces, mind the = vs == trap, and compare Strings with .equals(), and your conditional logic will stay clear and bug-free.
A nested if-else is an if-else placed inside the if or else block of another if-else. It evaluates a second condition only after the first has been resolved, making it ideal for dependent decisions such as finding the largest of three numbers or assigning a grade band.
An if-else-if ladder checks a sequence of independent conditions and stops at the first true one. A nested if-else evaluates an inner condition only when the outer condition is already true, so it models dependent decisions rather than a flat list of choices.
Yes. The ternary operator (condition ? valueIfTrue : valueIfFalse) is a one-line shorthand for an if-else that returns a value. Use it for short assignments. For multiple statements or deeply nested logic, a full if-else block stays more readable.
You likely used the assignment operator = instead of the comparison operator ==. With a boolean variable, if(flag = true) compiles and is always true. Always use == for primitives, or .equals() for objects, inside conditions to compare rather than assign.
Use the .equals() method, such as if(name.equals("admin")), not ==. The == operator compares object references, so two String objects with the same text can return false. Use .equalsIgnoreCase() when you want a case-insensitive match.
A nested if places one if (or if-else) inside another: if (outer) { if (inner) { /* both true */ } }. The inner block only runs when the outer condition is true. Always wrap each level in braces so the compiler and the reader agree on which else pairs with which if.
Java sets no hard limit on nesting depth, so you can nest as deeply as needed. In practice, keep it to two or three levels — beyond that, readability drops fast. Refactor deeper logic into separate methods, guard clauses (early returns), or a switch to keep the code maintainable.
KaneAI - Testing Assistant
World’s first AI-Native E2E testing agent.

TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance