int num = 5;
if (num > 0) {
System.out.println("num is positive");
} else {
System.out.println("num is not positive");
}
In this example, the if
statement checks to see if the value of num
is greater than 0. If it is, the code inside the first set of curly braces ({ }
) will be executed and the message “num is positive” will be printed to the console. If num
is not greater than 0, the code inside the else
block will be executed and the message “num is not positive” will be printed.
An if-else
statement is a basic control flow construct that allows you to execute different blocks of code depending on whether a certain condition is true or false. It has the following syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
You can also include an optional else if
clause to check for additional conditions:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Leave a Reply