Java if else Statement
The if-else
statement in Java allows you to execute one block of code if a specified condition is true and a different block of code if the condition is false. This control structure is useful for making decisions in your program based on certain conditions.
Syntax of 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
}
- condition: A boolean expression that evaluates to either
true
orfalse
. - True Block: The code inside the first set of braces
{}
executes if the condition istrue
. - False Block: The code inside the second set of braces
{}
executes if the condition isfalse
.
Example of if-else
Statement
Here’s a simple example demonstrating the use of an if-else
statement:
public class IfElseStatementExample {
public static void main(String[] args) {
int number = 5;
// Using if-else statement to check if the number is positive or negative
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is not positive.");
}
}
}
Explanation
- Declaration: The variable
number
is declared and initialized with the value5
. - Condition Check: The
if
statement checks whethernumber > 0
. Since5
is greater than0
, the condition evaluates totrue
. - Execution: Because the condition is
true
, the code inside theif
block (System.out.println("The number is positive.");
) is executed. - Output: The output will be:
The number is positive.
Example with Different Conditions
Here’s another example that checks if a number is positive, negative, or zero using an if-else
statement:
public class IfElseStatementMultipleConditions {
public static void main(String[] args) {
int number = 0;
// Using if-else statement to check if the number is positive, negative, or zero
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.");
}
}
}
Explanation
In this example:
- The program checks three different conditions:
- If
number
is greater than0
(positive). - If
number
is less than0
(negative). - If
number
is equal to0
(zero).
- If
- Since
number
is0
, the output will be:The number is zero.
Summary
The if-else
statement is a fundamental control structure in Java that allows you to implement conditional logic in your programs. It enables you to choose between two paths of execution based on whether a certain condition is true or false. This makes your applications more dynamic and responsive to various input scenarios.