If-else Statement in Java
An if-else statement extends the basic if statement to provide an alternative block of code to execute when the condition is false.
Essentially, it tells your program: "If this condition is true, do this; otherwise, do that."
This control flow structure allows your program to choose between two blocks of code based on a condition.
Syntax of an if-else Statement
Here is the basic syntax of an if-else statement in Java:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
condition: A boolean expression (an expression that evaluates to either true or false).
code block (if): The set of statements that will be executed if the condition is true.
code block (else): The set of statements that will be executed if the condition is false.
How It Works
When an if-else statement is encountered, the condition inside the parentheses is evaluated:
If the condition is true, the code block inside the first set of curly braces {} is executed.
If the condition is false, the code block inside the else set of curly braces {} is executed.
Example of an if-else Statement
Let's look at a simple example to understand how an if-else statement works. Consider the following code:
public class Main {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
}
}
Explanation:
Declaration of the variable: We declare an integer variable number and assign it a value of -5.
The if statement: We check if number is greater than 0 using the condition number > 0.
Code block (if): If the condition is true, the code inside the first set of curly braces {} will execute, printing "The number is positive."
Code block (else): If the condition is false, the code inside the else set of curly braces {} will execute, printing "The number is not positive."
Since number is -5 (which is not greater than 0), the condition is false, and the output will be:
The number is not positive.
Summary
if-else statement: Executes one block of code if a condition is true and another block of code if the condition is false.
Condition: A boolean expression that determines which code block will be executed.
Code blocks: The statements that run depending on whether the condition is true or false, enclosed in curly braces {}.
The if-else statement is a powerful tool for making decisions in your Java programs.