Unit 2.3: Conditional Statements
Changing the Flow of Control
Normally, a program's code is executed sequentially, one statement after another. Selection statements (like if and if-else) are fundamental tools that change this sequential flow.
- Conditional statements allow a program to "branch" out. Depending on whether a condition is true or false, the computer can skip sections of code or run specific blocks, creating dynamic behavior.
They allow the program to follow different paths by executing specific segments of code based on the evaluation of a Boolean expression.
The if Statement (One-Way Selection)
An if statement executes a block of code only if its condition is true.
- One-way selection is used to "guard" a block of code. If the condition isn't met, the block is completely ignored, and execution continues with the next statement after the
ifblock.
Task: Using an if statement to check if a number is even.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input a number");
int x = sc.nextInt();
if (x % 2 == 0) {
System.out.println("You have input an even number");
}
System.out.println("Good bye!");
}
}
The if-else Statement (Two-Way Selection)
An if-else statement executes one block of code if the condition is true and a different block if it is false.
- Two-way selection ensures that exactly ONE of the two blocks will run. The program cannot run both, and it cannot run neither (unless the program crashes).
Task: Using if-else to determine voting eligibility.
int age = 16;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not yet eligible to vote.");
}
The if-else-if Ladder
This structure checks a series of conditions. As soon as a condition is true, its block is executed, and the rest of the ladder is skipped.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
Critical Thinking
Remove the else block in the above code and what the results when the input is 92, 82, 50?
How do you fix the code without adding the else block? Hint: How about adding additional relational operators in the if block?
Another example:
Task: Using multiple else if branches for specific value matching.
import java.util.Scanner;
public class MultipleIfElse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please input your age");
short age = sc.nextShort();
if (age == 13) {
System.out.println("Hey you are the youngest teenager I know!");
} else if (age == 14) {
System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
} else if (age == 15) {
System.out.println("Hey, you are now surfing the teen years!");
} else if (age == 16) {
System.out.println("Hey, you are in sweet sixteen!");
} else if (age == 17) {
System.out.println("Hey, one more year to vote..");
} else if (age == 18) {
System.out.println("Hey, You can vote now!!");
} else if (age == 19) {
System.out.println("Hey, you are the oldest teen I know!");
} else {
System.out.println("Glad to know you are " + age + " years old!");
}
sc.close();
}
}
Study the above example.
Do you really need the else block for all the if blocks?
Not really, it is sufficient to keep the last else block and the rest can be removed. Here is the modified version with only the last else block and both the code work with the same functionality.
Task: Refactoring a ladder into independent if statements.
import java.util.Scanner;
public class MultipleIfElse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please input your age");
short age = sc.nextShort();
if (age == 13) {
System.out.println("Hey you are the youngest teenager I know!");
}
if (age == 14) {
System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
}
if (age == 15) {
System.out.println("Hey, you are now surfing the teen years!");
}
if (age == 16) {
System.out.println("Hey, you are in sweet sixteen!");
}
if (age == 17) {
System.out.println("Hey, one more year to vote..");
}
if (age == 18) {
System.out.println("Hey, You can vote now!!");
}
if (age == 19) {
System.out.println("Hey, you are the oldest teen I know!");
} else {
System.out.println("Glad to know you are " + age + " years old!");
}
sc.close();
}
}
Point to note: Be thoughtful when you use the else if statement. Many a times the else if statement can be replaced with just another if statement. Using just the if statement reduces the clutter in your code so it is advisable to use just that. Also the above example is also good candidate to use switch statement instead of the if statement. However, switch statement is not part of APCSA syllabus.
Nested if...else Statement:
It is legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
- Nesting allows for hierarchical decisions. The inner condition is only evaluated if the outer condition is true, creating a logical "AND" relationship between the two checks.
The syntax for a nested if...else is as follows:
if (boolean_expression 1) { //Executes when the Boolean expression 1 is true if(boolean_expression 2) { //Executes when the Boolean expression 2 is true } }
Task: Implementing a nested if structure.
public class NestedIfExample {
public static void main(String args[]) {
int x = 30;
int y = 10;
if (x == 30) {
if (y == 10) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
- The
switchstatement and the conditional (ternary) operator? :are not part of the AP Computer Science A course and will not be on the AP Exam. They are included here as additional useful Java features.
The switch Statement
A switch statement allows a variable to be tested for equality against a list of values (cases). It provides a cleaner alternative to a long if-else-if ladder when the conditions are based on the value of a single variable.
Task: Using a switch statement for multi-way selection.
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
default:
System.out.println("Invalid grade");
}
Which one to use? if or switch?
Many an if else construct can be replaced with a switch statement. A switch statement is cleaner and easier to understand than a chained if else block. If a switch statement meets your need then use the switch statement instead of multiple if else blocks. The above if else example can be replaced with an equivalent functionality switch statement
Task: Converting a long if-else-if ladder into a switch statement.
import java.util.Scanner;
public class MultipleIfElse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please input your age");
short age = sc.nextShort();
switch (age) {
case 13: {
System.out.println("Hey, you are the youngest teenager I know!");
break;
}
case 14: {
System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
break;
}
case 15: {
System.out.println("Hey, you are now surfing the teen years!");
break;
}
case 16: {
System.out.println("Hey, you are in sweet sixteen!");
break;
}
case 17: {
System.out.println("Hey, one more year to vote..");
break;
}
case 18: {
System.out.println("Hey, You can vote now!!");
break;
}
case 19: {
System.out.println("Hey, you are the oldest teen I know!");
break;
}
default: {
System.out.println("Glad to know you are " + age + " years old!");
}
}
sc.close();
}
}
- The variable used in a switch statement could be a byte, short, int, char, enums or Strings.
- You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon (:).
- The value for a case must be the same data type as the variable in the switch.
- When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
- When a break statement is reached, the switch terminates, and the program of execution jumps to the next line following the switch statement.
- Not every case needs to contain a break. If no break appears, the program of execution will fall through to subsequent cases until a break is reached.
- A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator, is applied on a Boolean expressions. Based on the evaluation of the boolean expression, one of the two possible choices will be assigned to a variable which is using this operator. The operator is written as:
variable x = (expression) ? value if true : value if false
Following is the example:
Task: Using the ternary operator to identify odd or even numbers.
import java.util.Scanner;
public class OddEvenFinder {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(
"Please enter a number and our little program will tell you if you entered an odd or even number");
int a = sc.nextInt(); // this method will expect you to input an integer value on the console.
String kind = (a % 2 == 0) ? "even" : "odd";
System.out.println(a + " is an " + kind + " number");
}
}