Java Control Statements - Complete Guide
Master all Java control statements with detailed explanations, flowcharts, and practical examples. Control statements determine the flow of program execution based on conditions.
Decision Making
if, if-else, switch
Loop Control
for, while, do-while
Branch Control
break, continue, return
1. What are Control Statements?
Control statements in Java are used to control the flow of execution in a program based on certain conditions or loops. They allow programs to make decisions, repeat tasks, and change the normal sequential flow of execution.
Types of Control Statements
- Decision Making: if, if-else, else-if ladder, nested if, switch
- Loop Control: for, while, do-while, for-each
- Branch Control: break, continue, return
- Exception Handling: try, catch, finally, throw
- Jump Statements: goto (reserved but not used)
Key Characteristics
- Control flow based on boolean expressions
- Can be nested (control within control)
- Switch works with specific data types
- Loops require termination conditions
- Branch statements alter normal flow
- Essential for non-linear program flow
Quick Reference: All Control Statements
Here are all Java control statements categorized by type:
2. Control Statements Reference Table
This comprehensive table lists all Java control statements with their syntax, description, and usage:
| Statement | Syntax | Description | When to Use |
|---|---|---|---|
| Simple if | if (condition) { // code to execute } |
Executes code block only if condition is true | Single condition check |
| if-else | if (condition) { // if block } else { // else block } |
Executes one of two code blocks based on condition | Binary decisions (true/false) |
| else-if ladder | if (cond1) { // block 1 } else if (cond2) { // block 2 } else { // default block } |
Multiple conditions checked in sequence | Multiple exclusive conditions |
| Nested if | if (cond1) { if (cond2) { // inner block } } |
if statement inside another if statement | Complex conditional logic |
| Switch | switch (var) { case value1: // code break; default: // code } |
Multi-way branch based on variable value | Multiple values of same variable |
| Statement | Syntax | Description | When to Use |
|---|---|---|---|
| for loop | for (init; condition; update) { // code to repeat } |
Repeats code fixed number of times | Known iteration count |
| while loop | while (condition) { // code to repeat } |
Repeats while condition is true | Unknown iteration count |
| do-while | do { // code to repeat } while (condition); |
Executes once, then repeats while condition true | At least one execution needed |
| for-each | for (type var : collection) { // code } |
Iterates through arrays/collections | Iterating collections |
| Statement | Syntax | Description | When to Use |
|---|---|---|---|
| break | break; | Exits loop or switch statement | Early loop termination |
| continue | continue; | Skips current iteration, continues loop | Skip specific iterations |
| return | return value; | Exits method, returns value to caller | Method termination |
| labeled break | break label; | Breaks out of labeled loop | Nested loop control |
- Simple if: Single condition that may or may not execute
- if-else: Binary choice between two actions
- else-if ladder: Multiple mutually exclusive conditions
- Switch: Multiple values of same variable/expression
- for loop: Known number of iterations
- while loop: Condition-based, unknown iterations
3. Simple if Statement
The simplest form of decision-making statement. Executes a block of code only if the specified condition is true.
public class SimpleIfExample {
public static void main(String[] args) {
int age = 20;
// Simple if statement
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
System.out.println("Program continues...");
// Another example
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
if (number % 2 == 0) {
System.out.println("The number is even.");
}
// Multiple statements in if block
int score = 85;
if (score >= 80) {
System.out.println("Excellent score!");
System.out.println("You passed with distinction.");
System.out.println("Score: " + score);
}
// Real-world example: Checking authentication
boolean isAuthenticated = true;
String username = "john_doe";
if (isAuthenticated) {
System.out.println("Welcome, " + username + "!");
System.out.println("Loading your dashboard...");
}
// Single statement without braces (not recommended)
if (age > 18)
System.out.println("You are an adult.");
// Only this statement is part of if
System.out.println("This always executes.");
}
}
- Always use curly braces
{}even for single statements - Condition must evaluate to boolean (true/false)
- Code inside if executes only when condition is true
- Without braces, only the immediate next statement is part of if
4. if-else Statement
Provides two alternative paths of execution. Executes one block if condition is true, another block if false.
public class IfElseExample {
public static void main(String[] args) {
// Basic if-else
int number = 15;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
// Age classification
int age = 25;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
// Student grading system
int marks = 75;
if (marks >= 40) {
System.out.println("Result: Pass");
System.out.println("Congratulations!");
} else {
System.out.println("Result: Fail");
System.out.println("Better luck next time.");
}
// Authentication example
String username = "admin";
String password = "12345";
String inputUsername = "admin";
String inputPassword = "12345";
if (username.equals(inputUsername) && password.equals(inputPassword)) {
System.out.println("Login successful!");
System.out.println("Welcome to the system.");
} else {
System.out.println("Login failed!");
System.out.println("Invalid username or password.");
}
// Nested if-else (simple)
int x = 10, y = 20;
if (x > y) {
System.out.println("x is greater than y");
} else {
if (x < y) {
System.out.println("x is less than y");
} else {
System.out.println("x is equal to y");
}
}
// Ternary operator alternative (for simple cases)
int a = 5, b = 10;
String result = (a > b) ? "a is greater" : "b is greater or equal";
System.out.println(result);
}
}
5. else-if Ladder
Used when there are multiple conditions to check in sequence. Each condition is checked one by one until a true condition is found.
public class ElseIfLadderExample {
public static void main(String[] args) {
// Student grade calculator
int marks = 85;
char grade;
if (marks >= 90) {
grade = 'A';
System.out.println("Excellent! Grade: " + grade);
} else if (marks >= 80) {
grade = 'B';
System.out.println("Very Good! Grade: " + grade);
} else if (marks >= 70) {
grade = 'C';
System.out.println("Good! Grade: " + grade);
} else if (marks >= 60) {
grade = 'D';
System.out.println("Satisfactory. Grade: " + grade);
} else if (marks >= 40) {
grade = 'E';
System.out.println("Pass. Grade: " + grade);
} else {
grade = 'F';
System.out.println("Fail. Grade: " + grade);
}
// Day of week number to name
int dayNumber = 3;
String dayName;
if (dayNumber == 1) {
dayName = "Monday";
} else if (dayNumber == 2) {
dayName = "Tuesday";
} else if (dayNumber == 3) {
dayName = "Wednesday";
} else if (dayNumber == 4) {
dayName = "Thursday";
} else if (dayNumber == 5) {
dayName = "Friday";
} else if (dayNumber == 6) {
dayName = "Saturday";
} else if (dayNumber == 7) {
dayName = "Sunday";
} else {
dayName = "Invalid day";
}
System.out.println("Day " + dayNumber + " is " + dayName);
// Age category classification
int age = 25;
String category;
if (age < 0) {
category = "Invalid age";
} else if (age <= 12) {
category = "Child";
} else if (age <= 19) {
category = "Teenager";
} else if (age <= 35) {
category = "Young adult";
} else if (age <= 60) {
category = "Middle-aged";
} else {
category = "Senior citizen";
}
System.out.println("Age " + age + ": " + category);
// Number type classification
int num = 0;
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else {
System.out.println(num + " is zero");
}
// Employee bonus calculation
double salary = 50000;
int yearsOfService = 3;
double bonus = 0;
if (yearsOfService > 10) {
bonus = salary * 0.20;
} else if (yearsOfService > 5) {
bonus = salary * 0.15;
} else if (yearsOfService > 2) {
bonus = salary * 0.10;
} else {
bonus = salary * 0.05;
}
System.out.println("Bonus: $" + bonus);
}
}
- Order conditions from most specific to most general
- Use mutually exclusive conditions when possible
- Always include a final else block as default case
- Consider switch statement for multiple equality checks
- Keep ladder depth reasonable (max 5-7 levels)
6. Nested if Statement
An if statement inside another if statement. Used for complex decision-making with multiple dependent conditions.
public class NestedIfExample {
public static void main(String[] args) {
// University admission criteria
int marks = 85;
boolean hasRecommendation = true;
if (marks >= 80) {
System.out.println("Eligible for interview.");
if (hasRecommendation) {
System.out.println("With recommendation letter.");
System.out.println("High priority candidate.");
} else {
System.out.println("Without recommendation letter.");
System.out.println("Regular priority.");
}
System.out.println("Proceed to interview round.");
} else {
System.out.println("Not eligible for admission.");
}
// Loan eligibility check
int age = 30;
double salary = 50000;
boolean hasGoodCredit = true;
if (age >= 21 && age <= 60) {
System.out.println("Age criteria satisfied.");
if (salary >= 30000) {
System.out.println("Income criteria satisfied.");
if (hasGoodCredit) {
System.out.println("Credit check passed.");
System.out.println("LOAN APPROVED!");
System.out.println("Maximum loan amount: $" + (salary * 5));
} else {
System.out.println("Credit check failed.");
System.out.println("Loan rejected due to poor credit.");
}
} else {
System.out.println("Income too low for loan.");
}
} else {
System.out.println("Age criteria not satisfied.");
}
// Number classification with multiple conditions
int number = 15;
if (number != 0) {
System.out.println("Number is non-zero.");
if (number > 0) {
System.out.println("Number is positive.");
if (number % 2 == 0) {
System.out.println("Positive even number.");
} else {
System.out.println("Positive odd number.");
}
} else {
System.out.println("Number is negative.");
if (number % 2 == 0) {
System.out.println("Negative even number.");
} else {
System.out.println("Negative odd number.");
}
}
} else {
System.out.println("Number is zero.");
}
// User access control system
String role = "editor";
boolean isAuthenticated = true;
boolean hasTwoFactor = false;
if (isAuthenticated) {
System.out.println("User authenticated.");
if (role.equals("admin")) {
System.out.println("Admin access granted.");
System.out.println("Full system access available.");
} else if (role.equals("editor")) {
System.out.println("Editor access granted.");
if (hasTwoFactor) {
System.out.println("Two-factor verified.");
System.out.println("Can edit and publish content.");
} else {
System.out.println("Two-factor required for publishing.");
System.out.println("Can only edit drafts.");
}
} else {
System.out.println("Viewer access granted.");
System.out.println("Read-only access.");
}
} else {
System.out.println("Authentication required.");
System.out.println("Please login first.");
}
// Nested if with logical operators (alternative)
int x = 10, y = 20, z = 30;
if (x > y) {
if (x > z) {
System.out.println("x is largest");
} else {
System.out.println("z is largest");
}
} else {
if (y > z) {
System.out.println("y is largest");
} else {
System.out.println("z is largest");
}
}
}
}
7. Switch Statement
A multi-way branch statement that executes code based on the value of an expression. More efficient than else-if ladder for multiple equality checks.
public class SwitchExample {
public static void main(String[] args) {
// Basic switch with int
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day " + day + " is " + dayName);
// Switch with char
char grade = 'B';
String message;
switch (grade) {
case 'A':
message = "Excellent!";
break;
case 'B':
message = "Very Good!";
break;
case 'C':
message = "Good";
break;
case 'D':
message = "Pass";
break;
case 'F':
message = "Fail";
break;
default:
message = "Invalid grade";
break;
}
System.out.println("Grade " + grade + ": " + message);
// Switch with String (Java 7+)
String color = "RED";
String meaning;
switch (color.toUpperCase()) {
case "RED":
meaning = "Danger/Stop";
break;
case "GREEN":
meaning = "Safe/Go";
break;
case "YELLOW":
meaning = "Caution";
break;
case "BLUE":
meaning = "Information";
break;
default:
meaning = "Unknown color";
break;
}
System.out.println(color + " means: " + meaning);
// Switch without break (fall-through)
int month = 2;
int year = 2023;
int days = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
// Check for leap year
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("Invalid month");
break;
}
System.out.println("Month " + month + " has " + days + " days");
// Switch with multiple cases sharing same code
char operator = '+';
int num1 = 10, num2 = 5;
int result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Cannot divide by zero");
}
break;
default:
System.out.println("Invalid operator");
break;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
// Enhanced switch (Java 14+)
String season = "SUMMER";
String description = switch (season) {
case "WINTER" -> "Cold season";
case "SPRING" -> "Flowering season";
case "SUMMER" -> "Hot season";
case "AUTUMN" -> "Falling leaves";
default -> "Unknown season";
};
System.out.println(season + ": " + description);
}
}
- Expression must be byte, short, char, int, String, or enum
- Case values must be compile-time constants
- Case values must be unique within switch
- Use
breakto prevent fall-through (except when intentional) - Always include
defaultcase for unexpected values - Switch works with equality checks only (not ranges)
8. Common Mistakes and Best Practices
- Missing braces:
if (condition) statement1; statement2;(statement2 always executes) - Assignment instead of comparison:
if (x = 5)❌ (useif (x == 5)✅) - Missing break in switch: Causes fall-through to next case
- Dangling else problem: Else binds to nearest if
- Infinite loops:
while (true)without break condition - Switch with floating point: Not allowed in Java
Best Practices
- Always use braces
{}even for single statements - Keep conditions simple and readable
- Use switch for multiple equality checks
- Place most likely condition first in else-if ladder
- Avoid deep nesting (max 3-4 levels)
- Use final else/default for error handling
- Consider polymorphism for complex conditional logic
Performance Tips
- Switch is faster than else-if ladder for many cases
- Place most frequent condition first in if-else chain
- Avoid complex expressions in loop conditions
- Use
breakearly in switch when match found - Consider lookup tables for complex mappings
- Use
finalvariables in switch cases
public class ControlStatementsBestPractices {
public static void main(String[] args) {
// GOOD: Always use braces
if (condition) {
doSomething();
}
// GOOD: Simple readable conditions
boolean isValid = (age >= 18 && hasLicense);
if (isValid) {
allowDriving();
}
// GOOD: Switch for multiple equality checks
switch (userRole) {
case "ADMIN":
grantAdminAccess();
break;
case "EDITOR":
grantEditorAccess();
break;
default:
grantViewerAccess();
break;
}
// GOOD: Avoid deep nesting
if (!isAuthenticated) {
showLoginPage();
return; // Early return
}
if (!hasPermission) {
showError("Insufficient permissions");
return;
}
// Main logic here (no nesting)
processRequest();
// GOOD: Use polymorphism for complex logic
// Instead of:
// if (animalType.equals("DOG")) { bark(); }
// else if (animalType.equals("CAT")) { meow(); }
// Use:
// Animal animal = AnimalFactory.create(animalType);
// animal.makeSound();
// GOOD: Extract complex conditions to methods
if (isEligibleForDiscount(customer)) {
applyDiscount();
}
// GOOD: Use enums with switch
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
System.out.println("Start of week");
break;
// ... other cases
}
}
static boolean isEligibleForDiscount(Customer c) {
return c.getAge() >= 65 ||
c.isStudent() ||
c.getPurchaseCount() > 10;
}
}