Java for Beginners · Module 4: Control Flow
🎯 Making Decisions
So far every program ran line after line, in order. Real programs need to choose: if the marks are 40 or more, print “Pass”; otherwise print “Fail”. Java makes decisions with the if statement, which uses the true/false conditions you built in Lesson 13.
1️⃣ The Simple if
marks >= 40 ?
marks >= 40 ?
carry on after it
Figure 1: A simple if: the block runs only when the condition is true.
Syntax: if (condition) { statements }. The condition must be in brackets and must be a boolean.
public class IfDemo {
public static void main(String[] args) {
int marks = 56;
if (marks >= 40) {
System.out.println("You passed.");
}
System.out.println("Done.");
}
}
You passed.
Done.
- The condition
marks >= 40is true, so the block runs. Done.is outside the braces, so it prints no matter what.- Always use braces
{ }, even for one statement. It avoids bugs when you add lines later.
2️⃣ if – else
Use else when you need exactly one of two outcomes.
public class IfElseDemo {
public static void main(String[] args) {
int number = 17;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
int age = 16;
if (age >= 18) {
System.out.println("Can vote");
} else {
System.out.println("Cannot vote yet, wait " + (18 - age) + " years");
}
}
}
17 is odd
Cannot vote yet, wait 2 years
- Exactly one of the two blocks runs, never both and never neither.
- The even/odd test uses
%from Lesson 12: an even number leaves remainder 0 when divided by 2.
3️⃣ The else-if Ladder
| Form | Use it when | Branches run |
if | one optional action | 0 or 1 |
if - else | exactly two outcomes | exactly 1 |
if - else if - else | several outcomes, only one should run | exactly 1 (the first true one) |
nested if | a second question depends on the first | depends |
Figure 2: The four shapes of if statements.
When there are more than two outcomes, chain the tests. Java checks them from the top and runs the first block whose condition is true, then skips the rest.
| marks | >= 90? | >= 75? | >= 60? | >= 40? | Grade |
| 95 | yes | – | – | – | A |
| 82 | no | yes | – | – | B |
| 67 | no | no | yes | – | C |
| 45 | no | no | no | yes | D |
| 20 | no | no | no | no | F |
Figure 3: How the else-if ladder is evaluated for each mark.
Program 3: Grade calculator
public class GradeLadder {
public static void main(String[] args) {
int[] tests = {95, 82, 67, 45, 20};
for (int marks : tests) {
String grade;
if (marks >= 90) {
grade = "A";
} else if (marks >= 75) {
grade = "B";
} else if (marks >= 60) {
grade = "C";
} else if (marks >= 40) {
grade = "D";
} else {
grade = "F";
}
System.out.println(marks + " -> " + grade);
}
}
}
95 -> A
82 -> B
67 -> C
45 -> D
20 -> F
- The program tests five marks. The loop and array are covered in Lessons 19 and 21, so for now read it as “repeat this for each mark”.
- Because tests run top to bottom, 82 does not need to be written as “between 75 and 89”. The earlier test (>= 90) already failed.
- The final
elsecatches everything left over. - Order matters. If you put
marks >= 40first, every passing mark would become D.
4️⃣ Nested if
An if inside another if handles a second question that only matters when the first answer is yes.
public class NestedIf {
public static void main(String[] args) {
int age = 20;
boolean hasId = true;
if (age >= 18) {
if (hasId) {
System.out.println("Entry allowed");
} else {
System.out.println("Show your ID");
}
} else {
System.out.println("Too young");
}
int a = 12, b = 45, c = 30;
int largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= c) {
largest = b;
} else {
largest = c;
}
System.out.println("Largest of " + a + ", " + b + ", " + c + " = " + largest);
}
}
Entry allowed
Largest of 12, 45, 30 = 45
- The ID check happens only for adults.
- For the largest of three, the logical
&&from Lesson 13 checks thatabeats both others. If not, onlybandcremain to compare.
5️⃣ Braces and the Dangling else
Without braces, an if controls only the next one statement. Indentation does not matter to Java. An else belongs to the nearest if.
public class DanglingElse {
public static void main(String[] args) {
int x = 5;
if (x > 0)
System.out.println("positive");
System.out.println("this line always runs");
int y = -3;
if (y > 0)
if (y > 10)
System.out.println("big");
else
System.out.println("belongs to the inner if");
System.out.println("end");
}
}
positive
this line always runs
end
- The second
printlnlooks like part of theifbecause it is indented, but it is not. Only the first line belongs to it. - For
y = -3the outerifis false, so nothing inside runs. Theelsewas attached to the innerif, not the outer one, so no message prints. - Using braces everywhere removes this confusion.
6️⃣ Errors Beginners Meet
A stray else
public class Bad1 {
public static void main(String[] args) {
int x = 5;
if (x > 3)
System.out.println("big");
else
System.out.println("small");
else
System.out.println("never");
}
}
Bad1.java:8: error: ‘else’ without ‘if’
else
^
1 error
- Every
elseneeds its ownif. To test another condition, writeelse if (...).
Variable might not have been initialized
public class Bad3 {
public static void main(String[] args) {
String grade;
int marks = 50;
if (marks >= 40) {
grade = "Pass";
}
System.out.println(grade);
}
}
Bad3.java:8: error: variable grade might not have been initialized
System.out.println(grade);
^
1 error
- If the condition were false,
gradewould never get a value. Add anelsethat assigns it, or give it a starting value.
The semicolon after if: no error, wrong behaviour
public class Bad2 {
public static void main(String[] args) {
int x = 5;
if (x > 3);
{
System.out.println("always printed");
}
if (x > 100) ;
System.out.println("also always printed");
}
}
Bad2.java:4: warning: [empty] empty statement after if
if (x > 3);
^
Bad2.java:8: warning: [empty] empty statement after if
if (x > 100) ;
^
2 warnings
always printed
also always printed
- The
;ends theifwith an empty statement, so the next lines are not controlled by it. Evenx > 100is false, yet the message prints. Never put a semicolon right after the closing bracket ofif.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
if (x = 5) | Assignment, not comparison (a compile error in Java) | if (x == 5) |
if (x > 3); | Empty statement; the block always runs | Remove the semicolon |
| No braces, then adding a second line | Second line is not controlled by the if | Always use braces |
| Ladder in the wrong order | Wide tests catch everything first | Test the most specific condition first |
Comparing Strings with == | Compares references | Use equals() |
Separate ifs instead of else if | Several blocks may run | Use else if for exclusive choices |
❓ Frequently Asked Questions
Q1. Can an if condition be an int, like in C?
No. It must be a boolean. if (1) is a compile error in Java.
Q2. How many else-if blocks can I have?
As many as you need, but for many fixed values a switch (Lesson 17) is neater.
Q3. Is else compulsory?
No. An if can stand alone.
Q4. What is the difference between else if and separate ifs?
In an else-if chain only the first true block runs. With separate ifs every true block runs.
✅ Key Takeaways
ifruns a block when its boolean condition is true.elsegives the other path, andelse ifadds more tests, checked top to bottom.- Only the first true block in a ladder runs.
- Always use braces. Never put
;after the condition. - An
elsebelongs to the nearestif.
🎓 Practice questions: (1) Write a program that reads a number and prints whether it is positive, negative or zero. (2) Check whether a year is a leap year (divisible by 4, but not by 100 unless also by 400). (3) Read three sides and print whether they form a triangle. (4) Why does the order of tests matter in an else-if ladder? (5) Find the bug: if (marks > 40); System.out.println("Pass");
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java