if else
if else
https://www.geeksforgeeks.org/loops-in-
java/?ref=lbp
Decision-making in Java helps to write decision-driven statements
and execute a particular set of code based on certain conditions.
The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it
won’t. In this article, we will learn about Java if-else.
If-Else in Java
If- else together represents the set of Conditional statements in
Java that are executed according to the condition which is true.
Syntax of if-else Statement
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Java if-else Flowchart
if-else Program in Java
Dry-Run of if-else statements
1. Program starts.
2. i is initialized to 20.
3. if-condition is checked. 20<15, yields false.
4. flow enters the else block.
4.a) "i is greater than 15" is printed
5. "Outside if-else block" is printed.
Below is the implementation of the above statements:
Java
// Java program to illustrate if-else statement
class IfElseDemo {
public static void main(String args[])
{
int i = 20;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
Output
i is greater than 15
Outside if-else block
// Driver Class
public class AgeWeightExample {
// main function
public static void main(String[] args) {
int age = 25;
double weight = 65.5;
Output
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.
Java
// Java program to illustrate if-else-if ladder
import java.io.*;
class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;
// condition 1
if (i == 10)
System.out.println("i is 10\n");
// condition 2
else if (i == 15)
System.out.println("i is 15\n");
// condition 3
else if (i == 20)
System.out.println("i is 20\n");
else
System.out.println("i is not present\n");
System.out.println("Outside if-else-if");
}
}
Output:
i is 20
Outside if-else-if
import java.io.*;
class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;
// condition 1
if (i < 10)
System.out.println("i is less than 10\n");
// condition 2
else if (i < 15)
System.out.println("i is less than 15\n");
// condition 3
else if (i < 20)
System.out.println("i is less than 20\n");
else
System.out.println("i is greater than "
+ "or equal to 20\n");
System.out.println("Outside if-else-if");
}
}
Output:
i is greater than or equal to 20
Outside if-else-if