In Java, the if-else statement is a crucial control flow mechanism that enables the execution of different code blocks based on specified conditions. It allows developers to direct the program's behavior by evaluating boolean expressions and executing corresponding code segments. This blog post will delve into the syntax, usage, and examples of various forms of if-else statements in Java.
Basic If Statement -
The if statement serves as a conditional test in Java programming. When the specified condition evaluates to true, it triggers the execution of the code block contained within the if statement's scope. If the condition is false
, the block of code is skipped.
Syntax:
if (condition) {
// if the condition is true, code in this block is executed
}
Example:int x = 20;
if (x > 18) {
System.out.println("x is greater than 18");
}
In this example, the condition x > 18 evaluates to true, so the message "x is greater than 18" is printed.Syntax:
if (condition) {
// if the condition is true, code in this block is executed
} else {
// bif the condition is false, code in this block is executed
}
Example:int age = 58;
if (age > 60) {
System.out.println("x is a senior citizen");
} else {
System.out.println("x is not a senior citizen");
}
Syntax:
if (condition1) {
// if the condition1 is true, code in this block is executed
} else if (condition2) {
// if the condition2 is true, code in this block is executed
} else if (condition3) {
// if the condition3 is true, code in this block is executed
} else {
// if all conditions are false, code in this block is executed
}
Example:int percentage= 65;
int division;
if (percentage>= 75) {
division = 1;
} else if (percentage >= 60) {
division = 2;
} else if (percentage >= 50) {
division = 3;
} else if (percentage >= 40) {
division = 4;
} else {
division = 0;
}
System.out.println("Division = " + grade);
Syntax:
if (condition1) {
// if the condition1 is true, code in this block is executed
if (condition2) {
// if the condition2 is true, code in this block is executed
}
}
Example:int percentage = 55;
int birthyear= 2014;
if (percentage >= 50) {
if (birthyear < 2015) {
System.out.println("Student is eligible for admission.");
} else {
System.out.println("Student must be born in or year 2015 for admission.");
}
} else {
System.out.println("Student must have 50 percent for admission.");
}