Java If Else
Java if...else statements are used to perform different actions based on different conditions. They help control the flow of a program and allow decision making.
Java If Statement
The if statement is used to check a condition. If the condition is true,
the code inside the block will be executed.
Example
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}
}
}
Try this code
Java If Else Statement
The if...else statement executes one block of code if the condition is true,
and another block if it is false.
Example
public class Main {
public static void main(String[] args) {
int x = 3;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
}
}
Try this code
Java Else If Statement
Use else if to check multiple conditions.
Example
public class Main {
public static void main(String[] args) {
int x = 5;
if (x > 5) {
System.out.println("Greater than 5");
} else if (x == 5) {
System.out.println("Equal to 5");
} else {
System.out.println("Less than 5");
}
}
}
Try this code
Nested If Statements
You can use an if statement inside another if statement.
Example
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
if (x < 15) {
System.out.println("x is between 5 and 15");
}
}
}
}
Try this code
Short Hand If (Ternary Operator)
Java provides a short way to write simple if...else statements using the ternary operator.
Example
public class Main {
public static void main(String[] args) {
int x = 10;
String result = (x > 5) ? "Greater" : "Smaller";
System.out.println(result);
}
}
Try this code
Why If Else is Important
- It helps in decision making
- It controls the flow of a program
- It is used in almost every program
- It makes programs dynamic and logical