Java Nested If Statement
We can put if statement inside another if to create nested if. Below is the syntax to declare nested if
statement.
if(conditional expressional){
statement;
if(conditional expressional){
statement
Or
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition2 is true
Java Nested If Example
public class Demo {
public static void main(String[] args) {
int a = 20;
if (a>10) {
if (a>15) {
System.out.println("value is greater than 10 and 15");
else {
System.out.println("value is less than 10");
}
}
Output:
value is greater than 10 and 15
Exercise 1
Write a java program that allows the user to enter aa number the checks if a number is even, we also
need to check whether the number is divisible by 6. And if the number is odd, we need to check
whether the number is divisible by 3. Use nested if-else statements.
Exercise 2
Check if three numbers are equal or not using nested if statement
Input a=5
b=7
c=5