Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
The else if Statements
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
The else if statement takes the if statement functionality one step further. Instead of having two outcomes, the programmer can create as many outcomes as they like, each one with its own expression. Take a look at the use of the else if statement below.
ElseIfStatementExample.java
package exlcode;
public class ElseIfStatementExample {
public static int exampleVariableOne = 37;
public static void main(String[] args) {
// else if statements have to include boolean expressions
if (exampleVariableOne < 10 /* expression */) {
System.out.println("The number is smaller than 10");
} else if (exampleVariableOne < 20 /* expression */) {
System.out.println("The number is between 10 and 20");
} else if (exampleVariableOne < 30 /* expression */) {
System.out.println("The number is between 20 and 30");
} else {
System.out.println("The number is larger than 30");
}
}
}
Each else if statement has its own expression that returns true or false. Only the FIRST expression that evaluates to "true" is executed. As we see above, if the expression exampleVariableOne < 10 returns a value of "true", only the statements within the curly brackets of the if statement are executed, and all the statements that follow are ignored. If none of the expressions evaluate to "true", the statement inside the curly braces of the else statement are executed. Remember these vital rules when working with if statements:
The if statement may contain zero or one else statement that must come after any else if expressions.
The if statement may have zero or more else if expressions that must come before the else statement.
Once the expression in an else if statement evaluates to true, all the remaining else if and else expressions are ignored.