In Java, an if-else statement is a control flow statement that allows you to execute a block of code if a particular condition is true, and a different block of code if the condition is false.
The basic syntax of an if-else statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Here, condition
is an expression that is evaluated to either true or false. If the condition is true, the block of code within the first set of curly braces is executed. If the condition is false, the block of code within the second set of curly braces (the else block) is executed.
For example, consider the following code that uses an if-else statement to determine if a number is even or odd:
int number = 5;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
In this case, the condition number % 2 == 0
is evaluated. If the remainder of number
divided by 2 is equal to 0, the first block of code is executed and the number is determined to be even. Otherwise, the second block of code is executed and the number is determined to be odd.
You can also use nested if-else statements to handle more complex conditions. In this case, you can have an if statement within another if statement or within an else block.
If-else statements are a fundamental programming construct that allows you to control the flow of your program and perform different actions based on different conditions.