Java If Else
Java If-Else statement is used to execute on of the two code blocks based on a given condition.
In this tutorial, we will learn the syntax and examples for if else statement.
Syntax
The syntax of if else statement is
if(condition) {
//if code block
} else {
//else code block
}
If the condition
evaluates to true
, if code block is executed.
If the condition
evaluates to false
, else code block is executed.
Flow Diagram of “if else” statement
The following flow diagram depicts the execution flow of an if-else statement in Java.
Examples for “if else ” statement in Java
1. Check if given number is positive using If Else statement in Java
In the following example, we are checking the condition that if x
is a positive number of not. We also have an else block accompanying if block. The condition in the if else statement would be x > 0
. The if block executes if the condition is true, or else, the else block executes.
Main.java
public class Main {
public static void main(String[] args) {
int x = -2;
if(x > 0){
System.out.println("x is positive.");
} else {
System.out.println("x is not positive.");
}
}
}
Output
x is not positive.
2. Check if given string contains “World” using If Else statement in Java
In the following example, we will check if given string contains “World” as substring, using if-else statement. If x is the given string, then the condition for if else statement is x.contains("World")
.
Main.java
public class Main {
public static void main(String[] args) {
String x = "Hello World";
if(x.contains("World")) {
System.out.println("x contains \"World\".");
} else {
System.out.println("x does not contain \"World\".");
}
}
}
Output
x contains "World".
Nested If-Else Statement
Since If-Else is just another statement in Java, we can write an If-Else statement inside another If-Else statement. Since an If-Else statement is nested in another If-Else, we may call this as Nested If-Else statement.
In the following example, we have written a Nested If-Else statement.
Main.java
public class Main {
public static void main(String[] args) {
int a = 3;
if(a % 2 == 1) {
System.out.println("a is odd number.");
if(a<10) {
System.out.println("a is less than 10.");
} else {
System.out.println("a is not less than 10.");
}
} else {
System.out.println("a is even number.");
}
}
}
Run the program and you will get the following output in console.
Output
a is odd number.
a is less than 10.
Conclusion
In this Java Tutorial, we learned how to write an If-Else statement, nested if-else statement, and presented some Java examples.