Java Decision Making
Java - Decision Making
Section titled “Java - Decision Making”Decision making structures allow your program to choose different paths of execution based on whether certain conditions are true or false. Java provides several statements for this:
ifstatements (includingif-elseandif-else if-else)switchstatements (including traditionalswitchand modernswitchexpressions)
The if Statement
Section titled “The if Statement”The simplest decision-making statement. It executes a block of code only if a specified boolean expression evaluates to true.
Syntax:
Section titled “Syntax:”if (boolean_expression) { // Statements to execute if the expression is true}// Code here executes regardlessIf the boolean_expression is true, the code inside the curly braces {} is executed. If it’s false, that block is skipped, and execution continues after the if statement’s closing brace.
Example:
Section titled “Example:”public class BasicIfExample { public static void main(String[] args) { int score = 75;
if (score >= 60) { System.out.println("Congratulations, you passed!"); }
System.out.println("Execution continues..."); }}Output:
Congratulations, you passed!Execution continues...The if-else Statement
Section titled “The if-else Statement”An if statement can be followed by an optional else block. The else block executes only when the if statement’s boolean expression is false.
Syntax:
Section titled “Syntax:”if (boolean_expression) { // Executes when the boolean expression is true} else { // Executes when the boolean expression is false}Example:
Section titled “Example:”public class IfElseExample { public static void main(String[] args) { int temperature = 15;
if (temperature > 25) { System.out.println("It's a hot day!"); } else { System.out.println("It's not too hot today."); } }}Output:
It's not too hot today.The if-else if-else Statement
Section titled “The if-else if-else Statement”Used to check multiple conditions sequentially. The first condition that evaluates to true has its corresponding block executed, and the rest of the else if and else blocks are skipped. The final else block (optional) executes if none of the preceding if or else if conditions are true.
Key points:
- An
ifcan have zero or moreelse ifblocks. - An
ifcan have zero or oneelseblock, which must come after allelse ifblocks. - As soon as an
iforelse ifcondition is met, its block executes, and the entire structure is exited.
Syntax:
Section titled “Syntax:”if (condition_1) { // Executes if condition_1 is true} else if (condition_2) { // Executes if condition_1 is false and condition_2 is true} else if (condition_3) { // Executes if conditions 1 and 2 are false, and condition_3 is true} else { // Executes if none of the above conditions are true (optional)}Example:
Section titled “Example:”public class GradingExample { public static void main(String[] args) { int score = 85; char grade;
if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Your grade is: " + grade); }}Output:
Your grade is: BNested if-else Statements
Section titled “Nested if-else Statements”You can place an if or if-else structure inside another if or else block. This allows for more complex condition checking, but excessive nesting can make code hard to read.
Syntax Example:
Section titled “Syntax Example:”if (outer_condition) { // Outer condition is true if (inner_condition) { // Both outer and inner conditions are true } else { // Outer is true, inner is false }} else { // Outer condition is false}Example:
Section titled “Example:”public class NestedIfExample { public static void main(String[] args) { int age = 25; boolean hasLicense = true;
if (age >= 18) { System.out.println("Eligible to drive based on age."); if (hasLicense) { System.out.println("Authorized to drive."); } else { System.out.println("Needs a driving license."); } } else { System.out.println("Not eligible to drive yet."); } }}Output:
Eligible to drive based on age.Authorized to drive.The switch Statement
Section titled “The switch Statement”The switch statement allows a variable to be tested for equality against a list of values (cases). It can often be a cleaner alternative to long if-else if-else chains when checking a single variable against multiple constant values.
Traditional switch Statement (Pre-Java 14)
Section titled “Traditional switch Statement (Pre-Java 14)”Syntax:
Section titled “Syntax:”switch (expression) { case value1: // Statements for value1 break; // Crucial: exits the switch case value2: // Statements for value2 break; // ... more cases default: // Optional: executes if no case matches // Default statements // No break needed here if it's the last block}Key Rules (Traditional Switch):
Section titled “Key Rules (Traditional Switch):”- The
expressionmust evaluate to abyte,short,char,int, their corresponding wrapper types (Byte,Short,Character,Integer), anenumtype (since Java 5), or aString(since Java 7). - Each
casevalue must be a constant (literal orfinalvariable) compatible with the expression’s type. - Duplicate
casevalues are not allowed. - The
breakstatement is essential. If omitted, execution “falls through” to the next case’s statements until abreakor the end of theswitchis reached. This is a common source of bugs. - The
defaultcase is optional and executes if none of thecasevalues match the expression. It can appear anywhere, but convention places it last. - If
defaultis not the last block, it needs abreakto prevent fall-through.
Example (Traditional Switch):
Section titled “Example (Traditional Switch):”public class TraditionalSwitchExample { public static void main(String[] args) { int dayOfWeek = 3; // 1=Sun, 2=Mon, ..., 7=Sat String dayName;
switch (dayOfWeek) { case 1: dayName = "Sunday"; break; case 2: dayName = "Monday"; break; case 3: dayName = "Tuesday"; break; case 4: dayName = "Wednesday"; break; case 5: dayName = "Thursday"; break; case 6: dayName = "Friday"; break; case 7: dayName = "Saturday"; break; default: dayName = "Invalid day"; break; // Good practice even if last } System.out.println("The day is: " + dayName); }}Output:
The day is: TuesdayExample (Fall-through Behavior):
Section titled “Example (Fall-through Behavior):”public class SwitchFallThrough { public static void main(String[] args) { char grade = 'B';
switch (grade) { case 'A': System.out.println("Excellent!"); break; case 'B': // No break here! case 'C': System.out.println("Well done"); break; case 'D': System.out.println("You passed"); break; case 'F': System.out.println("Better try again"); break; default: System.out.println("Invalid grade"); } // Output: Well done (because execution falls through from 'B' to 'C') }}Enhanced switch (Switch Expressions, Java 14+)
Section titled “Enhanced switch (Switch Expressions, Java 14+)”Java 14 introduced enhanced switch features, usable both as statements and expressions (that return a value). They offer a more concise syntax, eliminate fall-through by default, and improve code clarity.
Syntax (Arrow Form):
Section titled “Syntax (Arrow Form):”// As a statementswitch (expression) { case value1 -> // Single statement; case value2 -> { // Block of statements } // ... other cases default -> // Default statement or block;}
// As an expression (returning a value)ResultType result = switch (expression) { case value1 -> valueToReturn1; case value2, value3 -> valueToReturn2; // Multiple labels per case case value4 -> { // Complex logic in a block yield calculatedValue; // Use yield to return value from block } default -> defaultValue;}; // Note the semicolon needed for expressionKey Features (Enhanced Switch):
Section titled “Key Features (Enhanced Switch):”- Arrow syntax (
->): Code to the right of the arrow executes only for that case. No fall-through! - Multiple
caselabels: You can group multiple constants for the same execution block (e.g.,case 'B', 'C' -> ...). - No
breakneeded: The arrow syntax inherently prevents fall-through. - Exhaustiveness (for expressions): When used as an expression, the
switchmust cover all possible values of the expression (either throughcaselabels or adefaultbranch) to ensure a value is always returned. The compiler enforces this. yieldkeyword: Used inside a block ({}) on the right side of an arrow (->) to return a value for that case in a switch expression.
Example (Enhanced Switch Expression):
Section titled “Example (Enhanced Switch Expression):”public class EnhancedSwitchExample { public static void main(String[] args) { int dayOfWeek = 3; // 1=Mon, ..., 7=Sun
String dayType = switch (dayOfWeek) { case 1, 2, 3, 4, 5 -> "Weekday"; case 6, 7 -> "Weekend"; default -> { System.out.println("Invalid day number: " + dayOfWeek); yield "Unknown"; // Return value from block } };
System.out.println("Day type: " + dayType); }}Output:
Day type: WeekdayChoosing Between if-else if and switch
Section titled “Choosing Between if-else if and switch”- Use
if-else if-elsefor complex boolean conditions, range checks (score > 90), or checking multiple different variables. - Use
switch(especially enhanced switch) when checking a single variable against a set of discrete, constant values (int,String,enum). It can often be more readable in these scenarios.
What is Next?
Section titled “What is Next?”After understanding how to make decisions, the next chapter explores loop control statements (while, do-while, for), which allow you to execute blocks of code repeatedly.