Java if else if Statement
In Java, the if-else-if statement allows you to create a branching decision structure. It allows you to check multiple conditions and execute different code blocks based on those conditions.
Here is the basic syntax of the if-else-if statement in Java:
if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition1 is false and condition2 is true } else if (condition3) { // code to execute if condition1 and condition2 are false and condition3 is true } else { // code to execute if all conditions are false }
Each condition is checked in order, and the first condition that is true will cause its corresponding code block to be executed. If none of the conditions are true, the code in the else block will be executed.
Here is an example that uses the if-else-if statement to check the grade of a student and print a message based on their grade:
int grade = 85; if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else if (grade >= 70) { System.out.println("C"); } else if (grade >= 60) { System.out.println("D"); } else { System.out.println("F"); }
In this example, the program checks the value of the variable grade
and prints a message based on its value. If grade
is 85, the output will be "B", because the second condition (grade >= 80
) is true.