Skip to content

Module 3 · Control Flow and Arrays — topic 1 of 4

Conditional Statements

if, else if and else, nested conditions, combining conditions with logical operators, and writing clear, correct decision logic.

Beginner 12 min read·Lesson 9 of 39 in Java Programming

Learning objectives

  • Write if, if-else and else-if chains
  • Combine conditions with &&, || and !
  • Avoid the dangling-else and missing-brace traps

Definition

A conditional statement executes a block of code only when a boolean expression is true. Java's if statement requires the condition to be of type boolean.

Introduction

Programs constantly choose: is the password correct, is the stock low, did the student pass? The if statement is how Java makes those choices. Its syntax is the same as in C, with one important improvement: the condition must be a real boolean, so the classic C bug if (x = 5) does not compile.

Why it matters

Decision logic is where many business rules live — grading, discounts, validation — and small mistakes in boundaries (> versus >=) produce wrong results.

Clear conditions make code easier to test and review.

Detailed explanation

if (condition) { ... } runs the block when the condition is true. An optional else { ... } runs otherwise.

An else-if chain checks conditions in order and runs only the first block whose condition is true: if (m >= 90) ... else if (m >= 75) ... else .... Order matters — put the most specific or highest thresholds first.

Conditions are boolean expressions built from comparisons (< <= > >= == !=), method calls that return boolean (s.isEmpty(), list.contains(x)) and logical operators (&& || !).

Always use braces. Without them only the next single statement belongs to the if, and an else attaches to the nearest if — the *dangling else* problem.

Guard clauses handle special cases first and return early, keeping the main logic unindented: if (amount <= 0) return false;.

For many fixed values of one variable, a switch (next lesson) is often clearer than a long chain of else if.

Syntax

Java
if (marks >= 90) {
grade = 'A';
} else if (marks >= 75) {
grade = 'B';
} else if (marks >= 40) {
grade = 'C';
} else {
grade = 'F';
}
  • The condition must be boolean: if (count) is a compile error.
  • Only the first true branch of an else-if chain runs.
  • Use braces even for one-line bodies.

Code examples

Grading with an else-if chain

Java
public class Grade {
public static void main(String[] args) {
int[] scores = {95, 82, 40, 39};
for (int marks : scores) {
String grade;
if (marks >= 90) {
grade = "A";
} else if (marks >= 75) {
grade = "B";
} else if (marks >= 40) {
grade = "C";
} else {
grade = "F";
}
System.out.println(marks + " -> " + grade);
}
}
}
Output
95 -> A
82 -> B
40 -> C
39 -> F

Combining conditions

Java
public class Leap {
public static void main(String[] args) {
int[] years = {1900, 2000, 2024, 2026};
for (int y : years) {
boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
System.out.println(y + (leap ? " is" : " is not") + " a leap year");
}
}
}
Output
1900 is not a leap year
2000 is a leap year
2024 is a leap year
2026 is not a leap year

More examples

Validating a withdrawal with guard clauses

Java
public class Atm {
static String withdraw(long balance, long amount, boolean cardBlocked) {
if (cardBlocked) return "card blocked";
if (amount <= 0) return "invalid amount";
if (amount % 100 != 0) return "amount must be a multiple of 100";
if (amount > balance) return "insufficient funds";
if (amount > 20_000) return "daily limit is 20000";
return "dispensed " + amount + ", balance " + (balance - amount);
}
public static void main(String[] args) {
System.out.println(withdraw(5000, 2500, false));
System.out.println(withdraw(5000, 250, false));
System.out.println(withdraw(5000, 7000, false));
System.out.println(withdraw(50000, 25000, false));
System.out.println(withdraw(5000, 1000, true));
System.out.println(withdraw(5000, -100, false));
}
}
Output
dispensed 2500, balance 2500
amount must be a multiple of 100
insufficient funds
daily limit is 20000
card blocked
invalid amount

Step-by-step explanation

  • Each if checks one rule and returns a message immediately when the rule fails — a guard clause.
  • The order of the rules is part of the design: a blocked card is reported before anything else.
  • amount % 100 != 0 rejects amounts that the machine's notes can't make up.
  • Only when every check passes does the method reach the final return, which describes the successful withdrawal.
  • The calls in main exercise every branch once, which is a good habit when testing conditional logic.

Expected output

Running “Validating a withdrawal with guard clauses” prints exactly:

TextOutput
dispensed 2500, balance 2500
amount must be a multiple of 100
insufficient funds
daily limit is 20000
card blocked
invalid amount

Practical applications

  • Form validation before saving data
  • Pricing rules such as discounts and tax slabs
  • Access control: checking roles and permissions
  • Game logic: collisions, scores and win conditions

Best practices

  • Always use braces.
  • Test the boundary values of every condition (39, 40, 41).
  • Extract complex conditions into well-named boolean variables or methods.

Common mistakes

Wrong order in an else-if chain

Avoid

if (m >= 40) grade = 'C';
else if (m >= 75) grade = 'B'; // never reached for 80

Prefer

if (m >= 75) grade = 'B';
else if (m >= 40) grade = 'C';

Only the first true condition runs, so broader conditions must come after narrower ones.

Semicolon after the condition

Avoid

if (balance < 0);
System.out.println("overdrawn");

Prefer

if (balance < 0) {
System.out.println("overdrawn");
}

The semicolon is an empty statement that becomes the if's body, so the print always runs.

Important notes

  • Java has no truthiness: if (list) or if (count) doesn't compile; write if (!list.isEmpty()) or if (count != 0).
  • Comparing doubles with == is risky because of rounding; compare with a small tolerance instead.

Key takeaways

  • if/else-if/else runs the first branch whose condition is true.
  • Conditions must be boolean expressions.
  • Guard clauses and braces keep decision logic readable and safe.

Try it yourself

  1. 1
    Classify a triangle from three sides as equilateral, isosceles, scalene or invalid.
  2. 2
    Compute electricity charges with slabs: first 100 units ₹3, next 100 ₹5, rest ₹7.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy doesn't `int n = 1; if (n) { ... }` compile in Java?
  • BeginnerWhat is printed?
Practise this topic