Conditional Statements and Flow Control
Introduction to Control Flow Statements
In Java, there are a number of ways we can control the flow of the program. Control flow statements, change or break the flow of execution by implementing decision making statements.
All control flow statements are associated with a business condition – when true, the code block executes; when false it is skipped.
The decision making statements in Java are:
One-way if Statements.
Two-Way if-else Statements.
Multi-Way if-else Statements.
Switch Statement.
Overview - One-way if Statements
Practically all programming languages have some sort of if statement. The if statement is a one-way selection statement. You can use the logical operators &&, ==,||, ! (NOT) within control expressions in an if statement.
One-way if Statements
In this example (radius >= 0) is a control expression. The control expression must be placed in a set of parentheses. If the control expression is true, the statements in the body of the if statement execute. If the control expression is false, the statements in the body of the if statement are not executed.
One-way if Statements
All if statements contain a control expression to determine if the statements in the body of the if statement execute or not. In the example above, (mark >= 80) is the control expression. The control expression must be placed in a set of parentheses. If the control expression is true, the statements in the body of the if statement execute. If the control expression is false, then the statements in the body of the if statement are not executed.
One-way if Statements - Parentheses are Required
The Boolean expression following if must be enclosed in parentheses:
When there is only one statement to execute in the conditional, the curly braces are optional.
If there are multiple statements to execute as a block, the curly braces are essential.
Overview - The Two-Way if Statement
The if else statement is a two-way selection statement since either the block of code after the "if" part will be executed or the block of code after the "else" part will be executed.
An if-else Example
Multi-Way if-else Statements
This program contains an if statement that must choose from among three alternatives. The general form of a multi-way if-else statement is:
You can use as many if else lines as you need, and the final else is optional.
Multi-Way if-else Statements Illustration
Nested vs. Chained - if/else Statements
Trace if-else Statement – First Conditional
Use Correct Indentation
The else clause matches the most recent if clause in the same block.
Use Curly Braces When Needed
Nothing is printed from the preceding statement.
To force the else clause to match the first if clause, you must add a pair of braces:
Errant Semicolon
No need to use if to assign a Boolean
Unnecessary comparison to Boolean Literal
Calculate Body Mass Index
public class BMI {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Input weight in kilogram: ");
double weight = sc.nextDouble();
System.out.print("\nInput height in meters: ");
double height = sc.nextDouble();
// calculate bmi
double BMI = weight / (height * height);
// check range
if(BMI < 18.5)
System.out.println("Under weight");
else if(BMI >= 18.5 && BMI < 25)
System.out.println("Normal");
else if(BMI >= 25 && BMI < 30)
System.out.println("Overweight");
else
System.out.println("Obese");
System.out.print("\nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
}
}
Determining Leap Year
This program first prompts the user to enter a year as an int, and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
public class LeapYear {
public static void main(String[] args){
int year;
System.out.println("Enter an Year :: ");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
System.out.println("Specified year is a leap year");
else
System.out.println("Specified year is not a leap year");
}
Overview - switch Case Statement
A switch Case statement is used when we have a number of options, and we may need to perform a different task for each choice.
The switch Case statement is a branch statement. The case is a keyword that is used with the switch statement. It performs the execution of statement(s) when the value of the expression is matched with the case value, and the code of the particular statements are ended by a break keyword.
The syntax of the switch statement in Java:
switch Statement Flowchart
switch Statement: Example 1
/
When control reaches the switch statement, the program evaluates (grade / 10) (the switch expression).
Then it attempts to match the switch expression value to one of the case labels. If a match is found, the statement(s) following that case label are executed.
If no match is found, the default statement(s) (if there is a default case) will execute.
About the Case Labels
The switch expression is evaluated at runtime and may be any variable or expression.
The case labels are evaluated at compile-time and must be constants or literals.
This example uses String literals. Previous examples used int literals.
You can also use char literals and Enum types.
The break keyword terminates the switch statement.
If you omit the break statement, execution will fall through to the next case.
This example contains an unintended fall-through. Can you find it?
default case in Java switch-case
The switch statement also includes an optional default case. It is executed when the expression does not match any of the cases. For example:
switch Statement: char Example
switch Statement: enum Example
In the below example, we will explore how Enum keyword works, along with Switch case statements when Enum is declared outside main class.
Essential parts of the switch statement
switch expression - this is evaluated at runtime and must evaluate to an integer type, a string, a char, or an enum.
case labels - these must be literals or constants, and their type must match the type of the switch expression.
break statements - break (or return) statements must be used to prevent accidental fall-through.
default case - the default case is executed if no other case matches the value produced by the switch expression.
Chinese Zodiac
public static void main(String[] args) {
int year = 2022;
switch (year % 12)
{ case 0: System.out.println("monkey"); break;
case 1: System.out.println("rooster"); break;
case 2: System.out.println("dog"); break;
case 3: System.out.println("pig"); break;
case 4: System.out.println("rat"); break;
case 5: System.out.println("ox"); break;
case 6: System.out.println("tiger"); break;
case 7: System.out.println("rabbit"); break;
case 8: System.out.println("dragon"); break;
case 9: System.out.println("snake"); break;
case 10: System.out.println("horse"); break;
case 11: System.out.println("sheep");
}
}
Last updated