In Java, the if-else statement is used to control the flow of a program based on certain conditions.
It allows us to execute different blocks of code depending on whether a specified condition evaluates to true or false.
Here's the basic syntax of the if-else statement:
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 }
The condition is a boolean expression that evaluates to either true or false.
If the condition is true, the block of code within the if statement is executed.
If the condition is false, the block of code within the else statement (if present) is executed.
if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if condition1 is false and condition2 is true } else { // block of code to be executed if both condition1 and condition2 are false }
check the below example of a conditional if-else statement in Java to determine if a number is positive, negative, or zero
class ConditionalStatement { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("The number is positive"); } else if (number < 0) { System.out.println("The number is negative"); } else { System.out.println("The number is zero"); } } }
The number is positive
If number is greater than 0, the message "The number is positive" will be printed.
If number is less than 0, the message "The number is negative" will be printed.
If number is equal to 0, the message "The number is zero" will be printed.
The if-else statement is a fundamental construct in Java programming for making decisions and controlling the flow of execution based on different conditions.
public class ConditionStatementClass { public static void main(String[] args) { int num = 20; if (num > 0) { if(num % 2 == 0) { System.out.println("Positive even number"); } else { System.out.println("Positive odd number"); } } else if (num < 0) { if(num % 2 == 0) { System.out.println("Negative even number"); } else { System.out.println("Negative odd number"); } } else { System.out.println("The number is zero"); } } }
We can also use nested if-else else-if statements to handle multiple conditions scenarios.
Positive even number