if-else-if Statement
Lesson 4 of 11 in Coddy's Control Statements in Java course.
As of now, we know to write a decision statement for a true condition and a false condition, but if I want to decide based on two conditions, then we use an if-else-if statement.
If I want to decide whether or not to go to work based on whether or not it is raining, I would execute a false while also checking another condition, resulting in multiple else-ifs.
The if statement is followed by multiple else-if statements.
It is the chain of if-else statements that creates a decision tree where the program may enter the block of code where the condition is true.
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement; //executes when all the conditions are false
} Challenge
EasyWrite a program to accept an integer and check if the number is positive, negative or zero.
Use if-else-if statement and return POSITIVE, NEGATIVE or ZERO.
Try it yourself
class NumberCheck {
public static String numberCheck(int a1) {
// Write code here
}
}All lessons in Control Statements in Java
1What are Control Statements?
Introduction2Decision Making Statments
Simple if Statementif-else Statementif-else-if StatementNested if-StatementSwitch Case Statement