DEV Community

Pavitra Aravind
Pavitra Aravind

Posted on

Nested if

Java If Else Statement

In Java, if statement is used for testing the conditions. The condition matches the statement it returns true else it returns false. There are four types of If statement they are:

For example, if we want to create a program to test positive integers then we have to test the integer whether it is greater that zero or not.

In this scenario, if statement is helpful.

There are four types of if statement in Java:

if statement
if-else statement
if-else-if ladder
nested if statement
Enter fullscreen mode Exit fullscreen mode

if Statement

The if statement is a single conditional based statement that executes only if the provided condition is true.

If Statement Syntax:

if(condition)
{

//code
}

We can understand flow of if statement by using the below diagram. It shows that code written inside the if will execute only if the condition is true.

if-else Statement

The if-else statement is used for testing condition. If the condition is true, if block executes otherwise else block executes.

It is useful in the scenario when we want to perform some operation based on the false result.

The else block execute only when condition is false.

Syntax:

if(condition)
{

//code for true

}
else
{

//code for false

}

if else Example:

In this example, we are testing student marks, if marks is greater than 65 then if block executes otherwise else block executes.

public class IfElseDemo1 {

public static void main(String[] args)
{

int marks=50;

if(marks > 65)
{

System.out.print("First division");

}

else
{

System.out.print("Second division");

}
}

}

if-else-if ladder Statement

In Java, the if-else-if ladder statement is used for testing conditions. It is used for testing one condition from multiple statements.

When we have multiple conditions to execute then it is recommend to use if-else-if ladder.

Syntax:

if(condition1)
{

//code for if condition1 is true

}
else if(condition2)
{

//code for if condition2 is true

}

else if(condition3)
{

//code for if condition3 is true

}

...

else
{

//code for all the false conditions

}

Nested if statement

In Java, the Nested if statement is a if inside another if. In this, one if block is created inside another if block when the outer block is true then only the inner block is executed.

Syntax:

if(condition)
{

//statement
if(condition)
{

//statement
}

}

Top comments (0)