Making Decisions in Code
So far, our programs have followed a straight path from top to bottom. But what if you need your program to do different things based on different conditions? This is where decision-making comes in.
Decision-making structures allow your program to execute specific blocks of code based on whether a condition is true or false. This is the heart of creating dynamic and intelligent applications. In this chapter, we will explore the fundamental tools Java provides for this.
The Simple Branch
The if statement is the most basic decision-making tool. It tells the program to execute a certain block of code only if a specific condition evaluates to true. If the condition is false, the block is simply skipped.
Syntax
if (condition) {
// This code runs ONLY if the condition is true
}
Flowchart
+-------------+
| Start |
| |
| Check Cond? |----> FALSE ----> Skip Block
| |
| +----> TRUE ----> Execute Block
| |
+------>------+
|
End
Example: Check a Number
public class IfExample {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
System.out.println("The number is positive.");
}
if (number < 0) {
System.out.println("The number is negative.");
}
if (number == 0) {
System.out.println("The number is zero.");
}
}
}
Best Practices
- Always use curly braces
{ }to define the block, even if it's only one line. - Keep conditions simple and readable.
- Avoid putting semicolons after the
if (condition).
Checking Multiple Conditions
When you have multiple conditions to check, an if-else if-else ladder is cleaner and more readable than writing many separate if statements. It checks each condition in sequence. The first block whose condition is true is executed, and if none are true, the final else block is executed.
Syntax
if (condition1) {
// Block 1
} else if (condition2) {
// Block 2
} else if (condition3) {
// Block 3
} else {
// Default Block
}
Example: Assigning a Grade
public class GradeExample {
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 score is " + score + ", which is a grade '" + grade + "'.");
}
}
The Two-Way Branch
The if-else statement provides a simple two-way branch. If the if condition is true, the first block is executed; otherwise, the else block is executed.
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example: Even or Odd?
public class EvenOddExample {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}
}
}
Decisions Inside Decisions
You can place an if statement inside another if statement. This is called a nested if. It's used to check multiple, layered conditions, for example, checking if a number is positive and, if so, also checking if it's even.
Example: Positive and Even?
public class NestedIfExample {
public static void main(String[] args) {
int number = 8;
if (number > 0) {
// This is the outer 'if' block
System.out.println("The number is positive.");
// This is the nested 'if' block
if (number % 2 == 0) {
System.out.println("And it's also an even number.");
}
}
}
}
A Cleaner Alternative to Many Ifs
The switch statement is a clean and efficient way to compare a single variable against multiple constant values. It works with byte, short, int, char, and String types. Each case represents a possible value, and the code for that case is executed if the variable matches. A default case catches all other values.
Syntax
switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// ... more cases
default:
// Code if no cases match
}
Example: Day of the Week
public class DayOfWeek {
public static void main(String[] args) {
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;
default:
dayName = "Weekend";
break;
}
System.out.println("Day " + day + " is: " + dayName);
}
}
The Shorthand If-Else
The ternary operator (? :) is a compact, shorthand for a simple if-else statement. It assigns a value to a variable based on a condition, all in a single line.
Syntax
variable = (condition) ? valueIfTrue : valueIfFalse;
Example: Find the Larger Number
public class TernaryExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
// Find the larger number in one line
int larger = (a > b) ? a : b;
System.out.println("The larger number is: " + larger);
}
}