Working with if-else Statements in Java
Course: Core Java Training
Topic: Working with if-else Statements
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Training Provider: JustAcademy
1. Introduction to if-else Statements
Decision-making is an important part of programming. A Java program often needs to perform different actions depending on whether a particular condition is true or false. For example, a program may check whether a student has passed an examination, whether a user is old enough to register, or whether an account balance is sufficient for a withdrawal.
Java provides conditional statements such as if, if-else, if-else-if, and nested if statements to control the flow of execution. These statements evaluate Boolean conditions and execute the appropriate block of code.
Learning Objectives
- Understand conditional statements and decision-making in Java.
- Learn the syntax and execution flow of an
if statement.
- Use
if-else to select between two alternatives.
- Apply
else-if ladders for multiple conditions.
- Understand nested conditional statements and block scope.
- Combine conditions using relational and logical operators.
- Identify common errors and write readable conditional code.
2. What Is an if Statement?
An if statement executes a block of code only when its condition evaluates to true. If the condition is false, Java skips the statement or block associated with the if.
Syntax
if (condition) {
// Statements executed when condition is true
}
The condition must be a Boolean expression that evaluates to either true or false. Unlike some other programming languages, Java does not automatically treat integers such as 0 or 1 as Boolean conditions.
Example: Checking a Number
public class IfExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
System.out.println("Program completed.");
}
}
Output
The number is positive.
Program completed.
Explanation: The expression number > 0 evaluates to true because the value is 10. Java executes the statement inside the if block and then continues with the statement after the block.
3. What Is an if-else Statement?
An if-else statement provides two alternative execution paths. Java executes the if block when the condition is true; otherwise, it executes the else block.
Syntax
if (condition) {
// Executed when condition is true
} else {
// Executed when condition is false
}
Exactly one of these two blocks is executed when the statement is reached. The else keyword does not have a condition of its own; it represents the alternative when the associated if condition is false.
Example: Pass or Fail
public class PassFailExample {
public static void main(String[] args) {
int marks = 35;
if (marks >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output
Fail
Explanation: The condition marks >= 40 is false because the student scored 35. Therefore, Java skips the if block and executes the else block.
4. Understanding the Execution Flow
An if-else statement follows a simple decision-making process.
- Java evaluates the condition inside the parentheses.
- If the condition is true, the statements inside the
if block execute.
- If the condition is false, the statements inside the
else block execute.
- After the selected block finishes, execution continues with the next statement.
Example
int age = 21;
if (age >= 18) {
System.out.println("Eligible to register.");
} else {
System.out.println("Not eligible to register.");
}
System.out.println("Thank you.");
Output:
Eligible to register.
Thank you.
Because the condition is true, the first block executes. The second block is skipped, but the final statement executes because it is outside the conditional statement.
5. Using Relational Operators in Conditions
Relational operators compare two values and return a Boolean result. They are commonly used inside if and if-else conditions.
| Operator |
Meaning |
Example |
Result |
== |
Equal to |
10 == 10 |
true |
!= |
Not equal to |
10 != 5 |
true |
> |
Greater than |
10 > 5 |
true |
< |
Less than |
3 < 5 |
true |
>= |
Greater than or equal to |
5 >= 5 |
true |
<= |
Less than or equal to |
4 <= 5 |
true |
Example: Comparing Two Numbers
public class ComparisonExample {
public static void main(String[] args) {
int first = 25;
int second = 40;
if (first > second) {
System.out.println("First is greater.");
} else {
System.out.println("Second is greater or equal.");
}
}
}
Output:
Second is greater or equal.
The condition is false because 25 is less than 40. The else block executes. If the program must distinguish equality from a greater or smaller value, use separate conditions.
6. Using Logical Operators in Conditions
Logical operators combine or reverse Boolean conditions. They are useful when a decision depends on more than one requirement.
| Operator |
Name |
Meaning |
Example |
&& |
Logical AND |
True only when both conditions are true. |
age >= 18 && hasId |
|| |
Logical OR |
True when at least one condition is true. |
hasPass || hasTicket |
! |
Logical NOT |
Reverses a Boolean value. |
!isBlocked |
Example: Checking Eligibility
public class EligibilityExample {
public static void main(String[] args) {
int age = 22;
boolean hasIdentityCard = true;
if (age >= 18 && hasIdentityCard) {
System.out.println("Eligible.");
} else {
System.out.println("Not eligible.");
}
}
}
Output:
Eligible.
Both conditions are true, so the complete logical AND expression evaluates to true.
7. The if-else-if Ladder
An if-else-if ladder is used when a program must choose from more than two alternatives. Java checks the conditions in order. The first condition that evaluates to true determines which block executes. Remaining conditions in the ladder are skipped.
Syntax
if (condition1) {
// First option
} else if (condition2) {
// Second option
} else if (condition3) {
// Third option
} else {
// Default option when no condition is true
}
Example: Grade Calculation
public class GradeExample {
public static void main(String[] args) {
int marks = 82;
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 if (marks >= 40) {
System.out.println("Grade D");
} else {
System.out.println("Fail");
}
}
}
Output
Grade B
Explanation: The first condition, marks >= 90, is false. The second condition, marks >= 75, is true, so Java prints Grade B and skips the rest of the ladder.
Why Condition Order Matters
In a grade ladder, check higher thresholds before lower thresholds. If the program checks marks >= 40 first, a score of 82 will match that condition and print Grade D before Java reaches the higher grade conditions.
8. Nested if-else Statements
A nested conditional is an if or if-else statement placed inside another conditional block. Nested conditions are useful when a second decision should be considered only after a first requirement is met.
Syntax
if (outerCondition) {
if (innerCondition) {
// Both conditions are true
} else {
// Outer condition is true, inner condition is false
}
} else {
// Outer condition is false
}
Example: Login Validation
public class LoginExample {
public static void main(String[] args) {
boolean usernameValid = true;
boolean passwordValid = false;
if (usernameValid) {
if (passwordValid) {
System.out.println("Login successful.");
} else {
System.out.println("Incorrect password.");
}
} else {
System.out.println("Invalid username.");
}
}
}
Output:
Incorrect password.
The username condition is true, so Java enters the outer block. The password condition is false, so the inner else block executes.
9. The Dangling else Problem
When conditional statements are nested without braces, it may be unclear which if an else belongs to. In Java, an else is associated with the nearest preceding unmatched if.
Example Without Braces
int x = 10;
int y = 5;
if (x > 0)
if (y > 0)
System.out.println("Both are positive.");
else
System.out.println("Outer condition was true, inner was false.");
In this example, the else belongs to if (y > 0), not to if (x > 0).
Best practice: Always use braces around conditional blocks, even when a block contains only one statement. Braces improve readability and help prevent accidental changes to program logic.
10. Scope of Variables Declared Inside Conditional Blocks
A local variable declared inside a block is generally accessible only within that block and its nested blocks. It cannot normally be accessed after the closing brace.
public class ScopeExample {
public static void main(String[] args) {
if (true) {
int messageNumber = 10;
System.out.println(messageNumber);
}
// This would cause a compile-time error:
// System.out.println(messageNumber);
}
}
Output:
10
The variable messageNumber is declared inside the if block, so its scope ends when that block ends.
11. Common Mistakes When Using if-else
| Mistake |
Why It Is a Problem |
Correct Approach |
Using = instead of == for comparison |
Assignment is not the same as equality comparison; incompatible types may also cause a compile-time error. |
Use == for primitive equality comparisons. |
| Using a non-Boolean condition |
Java conditions must evaluate to a Boolean value. |
Use expressions such as count > 0 or Boolean variables. |
| Forgetting braces |
Only the next statement belongs to an unbraced conditional, which can cause logic errors. |
Use braces for all conditional blocks. |
| Putting conditions in the wrong order |
A broad condition may match before a more specific condition. |
Order range checks from the most specific or highest threshold to the broadest. |
Using a semicolon after if (condition) |
The semicolon creates an empty statement, so the intended following block is no longer controlled by that condition. |
Do not place an unnecessary semicolon after the condition. |
| Ignoring boundary values |
Values exactly at a threshold may be classified incorrectly. |
Choose >, >=, <, or <= according to the requirement. |
Comparing strings using == |
For objects, == checks reference identity rather than text equality. |
Use String.equals() for string-content comparison. |
| Overusing nested conditions |
Deep nesting can make code difficult to read. |
Use combined conditions or early-return patterns where appropriate. |
12. Comparing Strings in if-else Statements
Java strings are objects. When checking whether two strings contain the same text, use equals() rather than ==. The == operator checks whether two references identify the same object.
public class StringComparison {
public static void main(String[] args) {
String role = "admin";
if (role.equals("admin")) {
System.out.println("Administrator access.");
} else {
System.out.println("Standard access.");
}
}
}
Output:
Administrator access.
If a string might be null, calling equals() directly on it can cause a NullPointerException. A null-safe comparison for a known constant is:
String role = null;
if ("admin".equals(role)) {
System.out.println("Administrator access.");
} else {
System.out.println("Standard access.");
}
Output:
Standard access.
13. Practical Example: ATM Withdrawal
This example demonstrates how if-else statements can validate a withdrawal request and update an account balance.
public class ATMExample {
public static void main(String[] args) {
double balance = 5000.00;
double withdrawal = 1500.00;
if (withdrawal <= 0) {
System.out.println("Enter a valid withdrawal amount.");
} else if (withdrawal > balance) {
System.out.println("Insufficient balance.");
} else {
balance -= withdrawal;
System.out.println("Withdrawal successful.");
System.out.println("Remaining balance: " + balance);
}
}
}
Output
Withdrawal successful.
Remaining balance: 3500.0
Explanation
- The first condition rejects zero or negative withdrawal amounts.
- The second condition checks whether the withdrawal exceeds the available balance.
- The final
else executes only when both validation conditions are false.
- The compound assignment operator
-= subtracts the withdrawal amount from the balance.
In real financial applications, monetary values should be represented and validated carefully. This example is for learning conditional logic, not a complete banking implementation.
14. Practical Example: Find the Largest of Three Numbers
Nested conditions and logical operators can be used to compare multiple values and determine the largest number.
public class LargestNumber {
public static void main(String[] args) {
int a = 25;
int b = 40;
int c = 30;
if (a >= b && a >= c) {
System.out.println("Largest: " + a);
} else if (b >= a && b >= c) {
System.out.println("Largest: " + b);
} else {
System.out.println("Largest: " + c);
}
}
}
Output
Largest: 40
The first condition is false because 25 is not greater than or equal to 40. The second condition is true because 40 is greater than or equal to both 25 and 30. Therefore, Java prints 40.
15. if-else Versus the Conditional Operator
Java also provides the conditional operator ? :, which can select one of two values. It is useful for simple alternatives, while if-else is usually clearer for multi-step logic.
| Feature |
if-else |
Conditional Operator |
| Syntax |
Uses if and else blocks. |
Uses condition ? value1 : value2. |
| Purpose |
Controls execution of statements and blocks. |
Selects one of two expressions. |
| Multiple statements |
Can execute multiple statements in a block. |
Each branch is an expression, not a general statement block. |
| Readability |
Better for complex decisions. |
Useful for short, simple value selection. |
Example
int age = 20;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
// Equivalent value selection:
String category = age >= 18 ? "Adult" : "Minor";
System.out.println(category);
Both approaches select the same category. Use the form that makes the intention easiest to understand.
16. Best Practices for if-else Statements
- Use braces for every
if, else, and else-if block.
- Write clear Boolean conditions with meaningful variable names.
- Order range checks carefully, especially when assigning grades or categorizing values.
- Test values at the boundaries of each condition.
- Use
equals() to compare string contents.
- Avoid excessive nesting by combining related conditions or simplifying the logic.
- Use an
else block when a default alternative is needed.
- Do not confuse assignment (
=) with comparison (==).
- Keep each conditional block focused on one clear purpose.
- For complicated Boolean expressions, add parentheses to make the intended grouping clear.
17. Practice Exercises
Exercise 1: Positive, Negative, or Zero
Write a Java program that accepts an integer and uses an if-else-if ladder to determine whether the number is positive, negative, or zero.
Exercise 2: Even or Odd
Write a program that checks whether an integer is even or odd using the remainder operator %.
Exercise 3: Voting Eligibility
Declare an age variable and print whether a person is eligible to vote based on a minimum age of 18.
Exercise 4: Grade Calculator
Create an if-else-if ladder that assigns grades based on marks. Decide the ranges first and make sure the conditions are ordered correctly.
Exercise 5: Largest of Three Numbers
Compare three integers and print the largest. Make sure your program handles equal values correctly.
Exercise 6: Login Validation
Use Boolean variables to represent username and password validation. Print a successful login message only when both are valid.
Exercise 7: Discount Calculator
Apply a discount based on a purchase amount. Use multiple conditions to define discount ranges and print the final payable amount.
Exercise 8: Leap Year Check
Write a program to determine whether a year is a leap year. A year is a leap year if it is divisible by 400, or if it is divisible by 4 but not by 100.
18. Interview Questions and Answers
Q1. What is an if statement in Java?
An if statement executes a block only when its Boolean condition evaluates to true.
Q2. What is the purpose of an if-else statement?
It provides two alternative paths: one executes when the condition is true, and the other executes when the condition is false.
Q3. What is an if-else-if ladder?
It evaluates multiple conditions in sequence and executes the block belonging to the first condition that is true.
Q4. What is a nested if statement?
A nested if statement is a conditional statement placed inside another conditional block.
Q5. Can Java use an integer directly as an if condition?
No. Java requires the condition to evaluate to a Boolean value, either true or false.
Q6. What happens when no condition in an if-else-if ladder is true?
If a final else block is present, Java executes it. If there is no final else, Java skips the entire ladder.
Q7. Why should braces be used with if-else statements?
Braces clearly define the statements controlled by each condition and reduce the chance of logic errors when code is modified.
Q8. What is the difference between == and equals()?
For objects, == compares reference identity, while equals() can compare logical content. For strings, equals() is generally used to compare text.
Q9. Can an if statement exist without an else statement?
Yes. An if statement can execute a block only when a condition is true, without specifying an alternative block.
Q10. How can multiple conditions be checked together?
Use logical operators such as && for AND, || for OR, and ! for NOT.
Q11. What is the dangling else problem?
It is the ambiguity that can arise in nested conditionals without braces. Java associates an else with the nearest preceding unmatched if.
Q12. When should an if-else-if ladder be used?
Use it when a program must choose between several alternatives based on different conditions, such as grades, age categories, or discount levels.
19. Quick Revision Checklist
if executes a block only when its condition is true.
if-else selects between two alternative blocks.
else-if ladders support multiple alternative conditions.
- Nested conditions allow one decision to depend on another.
- Java conditional expressions must evaluate to Boolean values.
- Relational operators compare values; logical operators combine conditions.
- Use
equals() to compare string contents.
- Use braces to avoid ambiguity and accidental logic errors.
- Check boundary values and condition ordering.
- Use the conditional operator for simple value selection when it improves readability.
20. Official Learning Resources
21. Conclusion
The if-else statement is one of the most important decision-making tools in Java. It allows programs to respond to conditions, choose between alternatives, validate input, compare values, and implement business rules. By combining if, else, else-if, nested conditions, relational operators, and logical operators, developers can build clear and reliable program logic.
Practise the examples and exercises to strengthen your understanding of conditional execution. To continue learning Java, explore the Core Java Training Course, visit the JustAcademy website, or register for a course demo.