Chapter 722 min read
Java Decision Making & Control Flow
Mastering conditional branching with if-else logic, nested conditions, ternary expressions, and switch statements.
Released1995
Core MottoControl Program Flow with Precision
CreatorsOracle / Sun Microsystems
1. The if and if-else Statements
Decision-making structures evaluate boolean conditions to determine which execution path to take.
An if block runs only when its condition is true, while an optional else block handles false outcomes.
The Basic if & if-else Statements
Single Path (`if`):Executes a block of code strictly when the specified boolean expression evaluates to `true`.
Dual Path (`if-else`):Provides an alternative execution branch when the boolean condition evaluates to `false`.
Bracket Conventions:While curly braces `{}` are optional for single-line blocks, using them consistently is strongly recommended to prevent logic bugs.
java
public class Test {
public static void main(String args[]) {
int x = 30;
if (x < 20) {
System.out.print("This is if statement");
} else {
System.out.print("This is else statement");
}
}
}Real-World Decision Use Cases
Decision structures are fundamental to real-world software logic:
User Authentication:Verifying login credentials against stored records.
Access Control:Age and permission verification (e.g., voting eligibility).
E-Commerce Logic:Calculating tiered discounts and applicable sales taxes based on user spending thresholds.
2. Ladder & Nested Conditions
Complex decision paths use if-else-if ladders to test multiple distinct conditions in order.
Nested conditions embed conditional blocks inside other conditional blocks for multi-layered validation.
The if-else-if Ladder
Sequenced Checks:Evaluates conditions top-to-bottom. As soon as one condition evaluates to `true`, its block executes and the remaining ladder is skipped.
Key Rules:An `if` can have zero or many `else if` blocks, but only one final `else` block (which must be placed at the very end).
java
public class Test {
public static void main(String args[]) {
int x = 30;
if (x == 10) {
System.out.print("Value of X is 10");
} else if (x == 20) {
System.out.print("Value of X is 20");
} else if (x == 30) {
System.out.print("Value of X is 30");
} else {
System.out.print("This is else statement");
}
}
}Nested if Statements
Hierarchical Validation:An `if` or `else` block containing another `if` statement inside it.
Granular Control:Useful when secondary conditions only matter if a primary condition has already passed.
java
public class Test {
public static void main(String[] args) {
int x = 10, y = 20, z = 30;
if (x >= y) {
if (x >= z)
System.out.println(x + " is the largest.");
else
System.out.println(z + " is the largest.");
} else {
if (y >= z)
System.out.println(y + " is the largest.");
else
System.out.println(z + " is the largest.");
}
}
}3. The Conditional (Ternary) Operator
A shorthand inline alternative to standard if-else statements for returning or assigning values.
Ternary Syntax & Mechanics
Syntax:`variable = (condition) ? value_if_true : value_if_false;`
Evaluation Flow:First, the condition before `?` is evaluated. If `true`, the left value (before `:`) is produced. If `false`, the right value (after `:`) is produced.
Best Practice:Reserve ternary expressions for simple assignment checks to preserve readability.
java
public class Test {
public static void main(String args[]) {
int a = 10;
int b;
b = (a == 1) ? 20 : 30;
System.out.println("Value of b is : " + b); // Outputs 30
b = (a == 10) ? 20 : 30;
System.out.println("Value of b is : " + b); // Outputs 20
}
}4. The switch Statement & Fall-Through Logic
The switch statement tests a variable for equality against a list of constant case values.
Features fall-through execution behavior when break statements are omitted.
Switch Syntax & Supported Types
Supported Types:Primitive integers (`byte`, `short`, `int`, `char`), `String`, and `enum` constants.
Constant Case Values:Each `case` value must be a literal or constant of the same type as the target expression.
Fall-Through Behavior:Without a `break` statement, execution continues into subsequent cases regardless of whether they match.
java
public class Test {
public static void main(String args[]) {
char grade = 'C';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done"); // Matches 'C'
break;
case 'D':
System.out.println("You passed");
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}Data Type Diversity in Switch Statements
Integer & Primitive Matching:Traditional primitive matching across numerical types.
String Switches:Supported since Java 7 for clean text-based command or option parsing.
java
public class Test {
public static void main(String args[]) {
String grade = "C";
switch (grade) {
case "A":
System.out.println("Excellent!");
break;
case "B":
case "C":
System.out.println("Well done");
break;
default:
System.out.println("Invalid grade");
}
}
}The default Keyword Role
Catch-All Clause:Executes when no case value matches the tested expression.
Optional Placement:Typically placed at the bottom, though strictly optional. Omitting it when no cases match results in zero switch code execution.
java
public class SwitchWithDefault {
public static void main(String[] args) {
int month = 13; // Invalid month value
switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
default:
System.out.println("Invalid month"); // Executes here
}
}
}Classroom Discussion Starter
When should you prefer an if-else if ladder over a switch statement, and vice versa?
Takeaway Goal: Use switch statements when testing a single variable for exact equality against discrete constant values (ints, chars, Strings, Enums). Use if-else if ladders when conditions require range checks (e.g., score > 80), complex multi-variable logical expressions (&& / ||), or non-constant dynamic values.