Java if else Statement
The if-else statement in Java is used to execute one block of code if a specified condition is true and another block of code if the condition is false. The general syntax of an if-else statement is as follows:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
In this syntax, condition is a boolean expression that evaluates to either true or false. If the condition is true, the block of code inside the first set of curly braces {} is executed. If the condition is false, the block of code inside the second set of curly braces {} is executed instead.
Here is an example that uses an if-else statement to determine whether a number is positive or negative:
int num = -2;
if (num >= 0) {
System.out.println(num + " is a positive number");
} else {
System.out.println(num + " is a negative number");
}
In this example, the condition num >= 0 checks whether num is greater than or equal to 0, which is false in this case. Therefore, the block of code inside the second set of curly braces {} is executed, and the output is:
-2 is a negative number
If num were a positive number or zero, the condition would be true and the block of code inside the first set of curly braces {} would be executed instead.
