Understanding Control Flow And Conditionals In Java
How to tackle decision making in Java
Introduction
Control flow and conditionals are fundamental concepts in many programming languages, including Java. In computer programming, control flow refers to the order in which the statements in a program are executed.The basic execution of a program begins with the initial programming statement, then the program is executed one statement at a time until it is finished. Conditional statements are used to control the flow of a program by checking for certain conditions and then executing different blocks of code depending on the results of the checks. There are three types of control statements: selection, iteration and jump statements. In this article we will be focusing on selection statements.
Prerequisites:
Basic Java Syntax
Boolean expressions
Logical operators
What Are Selection Statements?
In Java, selection statements allow you to make decisions in your code based on certain conditions. A condition in programming is a logical statement or expression that evaluates to either true or false, influencing the execution of specific code blocks. A condition is also known as a boolean expression. There are three selection statements available in Java, namely if, if..else
and switch
. Here is a closer look at each of them.
The if
Statement
An if
statement is composed of the reserved word if
, a boolean expression, and then a statement. This basic selection statement allows you to execute a block of code if the condition(boolean expression) is true and any subsequent statements are then processed. If the condition is false, the statement it controls is skipped, and processing immediately moves on to the next statement.
The following is the syntax of the if
statement:
if (boolean expression) {
statement
}
Sample code:
int number = 5;
if (number > 0) {
System.out.println("The number is positive");
}
In the code block above:
'int number = 5;'
declares a variable named `number` and assigns it the value 5. Here, we assume that the value of `number` is 5.`if (number > 0) {`
: This line starts an `if
` statement. It checks the condition inside the parentheses, which is`number > 0`
. This condition checks if the value of `number` is greater than 0.`{`
: The opening curly brace indicates the beginning of the code block associated with the `if
` statement. If the condition in the `if
` statement is true, the code inside this block will be executed.`System.out.println("The number is positive");`
: This line is executed only if the condition in the`if`
statement is true. It prints the message "The number is positive" to the console.`}`
: The closing curly brace indicates the end of the code block associated with the`if`
statement. All the code inside the block is executed only if the condition in the `if
` statement is true.
In summary, this code block checks if the value of the variable `number
` is greater than 0. If it is, the program prints the message "The number is positive" to the console. If the value is not greater than 0, the code block is skipped, and no message is printed.
The if..else Statement
In the code block above we only handle one situation, that is, when the variable number is true. What if we want our code to handle the situation if it is false? This is where if..else
statement comes in. In the if..else statement, the first statement is carried out if the condition is true, and the second statement is carried out if the condition is false. A boolean condition can only evaluate to true or false, therefore only one or the other will be executed.
Syntax:
if (boolean expression) {
Statement 1
} else {
Statement 2
}
Sample code:
int number = 5;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
In the updated code, the `else
` statement is added after the closing curly brace of the `if
` block. The `else
` block is executed if the condition in the `if
` statement is false, meaning that the number is not greater than 0. In this case, the program will print the message "The number is not positive" to the console.
So, based on the assumption that the variable `number
` is 5, the condition `number > 0
` is true, and the message "The number is positive" will be printed. However, if the value of `number
` were less than or equal to 0, the condition would be false, and the message "The number is not positive" would be printed instead.
The else if Statement
The `else if
` statement is used to add additional conditional checks after an initial `if
` statement. It allows you to test multiple conditions and execute different blocks of code depending on which condition is true.
When an `if
` statement evaluates to false, the program proceeds to the next `else if
` statement (if present) and checks its condition. If the condition in an `else if
` statement is true, the corresponding code block associated with that `else if` statement is executed.
The `else if
` statement is useful when you have multiple mutually exclusive conditions and want to perform different actions based on those conditions. It provides a way to chain together multiple conditions and ensure that only one block of code executes, even if multiple conditions might be true. If none of the `if
` or `else if`
conditions are met, the program can proceed to an optional `else
` statement or continue executing the next part of the code.
Syntax:
if (condition 1) {
Statement 1
}else if (condition 2) {
Statement 2
} else {
Statement 3
}
Sample code:
int number = 5;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println(" The number is negative.");
} else {
System.out.println("The number is zero.")
}
In the updated code;
an `
else if
` statement is introduced between the `if` and `else` blocks. It allows for testing an additional condition when the initial condition(`number > 0`)
is falseIf the value of `number` is greater than 0, the program will execute the code block inside the first
`if`
statement and print "The number is positive."If the value of `number` is less than 0, the `else if` condition `
number < 0
` will be true, and the code block inside the `else if` statement will execute, printing "The number is negative."If neither the `
if
` condition nor the `else if
` condition is true, it means the value of `number` must be 0. In that case, the code block inside the `else` statement will execute, printing "The number is zero."
By using `else if
` statements, you can provide multiple conditional branches to handle different scenarios based on the value of `number`.
Nested if Statement
A nested if statement is used to create conditional branching within another if statement. It involves placing an if statement inside the code block of another if statement. This allows for more complex decision-making scenarios where certain conditions need to be further evaluated within specific branches.
Sample code:
int number = 5;
if (number > 0) {
System.out.println("The number is positive.");
if (number % 2 == 0) {
System.out.println("The number is positive and even");
} else {
System.out.println("The number is positive and odd");
}
}else if (number < 0) {
System.out.println(" The number is negative");
} else {
System.out.println("The number is zero");
}
In this updated code, a nested `if
` statement is added inside the first `if
` block. It checks whether the number is positive and then performs an additional check to determine if it is even or odd.
If the value of `number
` is positive, the program will execute the code block inside the outer `if`
statement and print "The number is positive." Then, it will proceed to the nested `if` statement. If the condition `number % 2 == 0
` evaluates to true, the program will print "The number is positive and even." Otherwise, if the condition is false, it will print "The number is positive and odd."
This example demonstrates how nested `if`
statements can be used to add further conditional checks within specific branches, allowing for more precise decision-making based on multiple conditions. However, it is important to use them judiciously, as they can make your code more difficult to read and understand.
The switch statement
The `switch
` statement in Java is a control flow construct that allows for multi-way branching based on the value of an expression. It provides an alternative to using multiple `if-else
` statements when comparing a single variable against multiple possible values.
The `switch
` statement evaluates the expression and compares it to different cases. Each case represents a specific value that the expression might match. When a match is found, the corresponding block of code associated with that case is executed. This allows for concise and efficient handling of multiple possible outcomes.
The `switch
` statement can be particularly useful when there are many possible values to compare against and when the code execution depends on distinct, discrete cases. It provides a cleaner and more readable way to express such branching logic.
To provide a default case, which is executed if none of the cases match, the `switch
` statement can include a `default
` case. This case is optional but recommended to handle scenarios where none of the specific cases match the expression's value.
It's important to note that the expression in a `switch
` statement must be of a compatible type, such as `char
`, `int
`, `enum
`, or `String
` (from Java 7 onwards). Additionally, the `break
` statement is used to exit the `switch
` block after executing a particular case to avoid fall-through to subsequent cases.
Syntax:
switch (expression) {
case value 1:
//code to execute if expression matches value 1
break;
case value 2:
//code to execute if expression matches value 2
break;
//more cases can be added as needed
default:
//code to execute if expression matches none of the cases
}
Sample code:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
Case 6:
System.out.println("Saturday");
break;
Case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
Let's break down the code step by step:
`
int day = 4;
`: This line declares an integer variable named `day` and assigns it the value 4. Here, we assume that the value of `day` represents a day of the week.`
switch (day) {
`: This line starts the `switch` statement and specifies the variable `day` as the expression to be evaluated.`
case 1:
`: This line sets up the first case. If the value of `day` is 1, the code following this case will be executed.`
System.out.println("Monday");
`: This line is executed only if `day` is 1. It prints "Monday" to the console.`
break;
`: The `break` statement is used to exit the `switch` statement. It ensures that the program will not continue executing subsequent cases. Here, it is used after each case to prevent fall-through.The code block repeats for cases 2 to 7, each representing a different day of the week. The corresponding day name is printed to the console for the respective case.
`
default:
`: This line sets up the default case. If the value of `day` does not match any of the specified cases, the code following this default case will be executed.`
System.out.println("Invalid day");
`: This line is executed if the value of `day` does not match any of the cases. It prints "Invalid day" to the console.
In summary, this code determines the day of the week based on the value of the `day` variable using a `switch` statement. The program checks the value of `day` and executes the code associated with the matching case. If none of the cases match, the program executes the code in the `default` case. In this specific example, with `day` set to 4, it prints "Thursday" to the console.
Overall, the `switch` statement offers a convenient and structured approach for multi-way branching in Java, making code more concise and readable in situations where multiple cases need to be evaluated based on the value of an expression.
Conclusion
When making decisions in Java, it is essential to carefully consider the conditions and logic to ensure that the appropriate code block is executed based on the desired outcomes. Proper use of these decision-making constructs helps control the flow of the program and allows for flexible and dynamic behavior based on specific conditions. I hope you enjoyed reading this article. Follow me for more beginner friendly articles on software development. You can also connect with me on other platforms. Here is my linktree✨