Last Updated : 03 Dec, 2024
Try it on GfG Practice
The if-else
statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true
and another block if the condition is false
. In this article, we will learn Java if-else statement
with examples.
Example:
Java
// Java Program to demonstrate
// if-else statement
public class IfElse {
public static void main(String[] args) {
int n = 10;
if (n > 5) {
System.out.println("The number is greater than 5.");
} else {
System.out.println("The number is 5 or less.");
}
}
}
The number is greater than 5.
Dry-Running the Above Example:
n
is initialized to 10
.if
condition is checked: 10 > 5
, yields true
.
if
statement executes: "The number is greater than 5."
is printed.else
block is skipped as the condition is true
.Working of if-else Statementif (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }
if
block.true
, go to Step 4.false
, go to Step 5.if
block or the body inside the if
is executed.false
, the else
block is executed instead.if-else
block.Below is the Java if-else flowchart.
In the above flowchart of Java if-else, it states that the condition is evaluated, and if it is true, the if
block executes; otherwise, the else
block executes, followed by the continuation of the program.
In Java, we can use nested if statements to create more complex conditional logic. Nested if statements are if statements inside other if statements.
Syntax of Nested ifif (condition1) { // code block 1 if (condition2) { // code block 2 } }
Example:
Java
// Java Program to implement
// Nested if statement
public class NestedIf {
public static void main(String[] args) {
int a = 25;
double w = 65.5;
if (a >= 18) {
if (w >= 50.0) {
System.out.println("You are eligible to donate blood.");
} else {
System.out.println("You must weigh at least 50 kilograms to donate blood.");
}
} else {
System.out.println("You must be at least 18 years old to donate blood.");
}
}
}
You are eligible to donate blood.
Note: The first print statement is in a block of "if" so the second statement is not in the block of "if". The third print statement is in else but that else doesn't have any corresponding "if". That means an "else" statement cannot exist without an "if" statement.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4