Java if else - control flow statements
Java, one of the most popular programming languages, offers a rich set of control flow statements that allow you to dictate the flow of your program. Among these, the if-else and switch statements are foundational tools for controlling program execution. Additionally, Java provides jump statements like break and continue to enhance the control flow. In this comprehensive guide, we'll explore these control flow statements in detail, providing you with the knowledge and skills needed to harness their full potential.
Understanding Control Flow
Before diving into the specifics of if-else, switch, break, and continue statements, it's crucial to understand the concept of control flow. Control flow refers to the order in which instructions are executed within a program. Control flow statements allow you to alter this order, enabling your program to make decisions and respond dynamically to different conditions.
The If-Else Statement :
The if-else statement is used for conditional execution. It evaluates a Boolean expression and executes a block of code if the expression is true, or an alternative block if it's false. Here's the basic syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example 1: Checking for Even or Odd
int number = 7;
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
Output
The number is odd.
Example 2: Determining Eligibility
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
Output
You are eligible to vote.
Nested If-Else
You can also nest if-else statements to handle more complex conditions. This involves placing one if-else statement inside another.
Let's consider a scenario where you want to determine a student's grade based on their exam scores. In this case, you have different conditions for different score ranges.
int score = 78;
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: C
In this code:
- The outermost if-else statement checks if score is greater than or equal to 90, assigning a grade of 'A' if true.
- Inside the else block of the outer if, there is another if-else statement that checks if score is greater than or equal to 80, assigning a grade of 'B' if true.
- This pattern continues with nested if-else statements, each checking a different score range and assigning the corresponding grade.
- If none of the conditions match, the final else block assigns a grade of 'F'.
The Switch Statement
The switch statement is another way to make decisions in Java. It's particularly useful when you have multiple conditions to check against a single value.
The switch statement evaluates an expression and then compares it against various cases. When it finds a match, it executes the corresponding block of code. Here's the basic syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// Additional cases
default:
// Code to execute if none of the cases match
}
Example : Days of the Week
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
// Add cases for the other days
default:
dayName = "Invalid day";
}
System.out.println("Today is " + dayName);
Output
Today is Tuesday
Switch vs. If-Else
When should you use a switch statement instead of if-else? The choice depends on the specific scenario:
Use if-else when:
- You need to evaluate complex conditions.
- Your conditions are not based on a single value.
- You need to check for ranges (e.g., checking if a number is between two values).
Use switch when:
- You have a single value to compare against multiple cases.
- You want to improve code readability for scenarios with many conditions.
Jump Statements: Break and Continue
In addition to if-else and switch statements, Java provides jump statements to control the flow of your program even further.
The Break Statement
The break statement is used to exit a loop or switch block prematurely. When break is encountered, the program jumps out of the loop or switch, and execution continues with the statement immediately following the loop or switch block.
Example: Using Break in a Loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}
Output
1
2
3
4
The Continue Statement
The continue statement is used to skip the current iteration of a loop and continue with the next iteration. It's often used to skip specific values or conditions within a loop.
Example: Using Continue in a Loop
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i is 3
}
System.out.println(i);
}
Output
1
2
4
5
Summary
Understanding control flow statements like if-else, switch, break, and continue is essential for Java developers. These statements empower you to write dynamic and responsive programs that make decisions based on various conditions and control the flow of your code efficiently. By mastering these tools, you'll enhance your ability to write efficient and readable code, making you a more proficient Java programmer.