If else nested and ladder if else statement in Java

If else is used to select a set of statements based on condition.

If the condition is true then the statement associated with if is executed, otherwise else part is executed.

It can also be used without else.

If , if else, switch are conditions statements that Java supports.

If else has variations it can be used as follows

  1. If Statement
  2. If Else Statement
  3. Nested If Else
  4. Ladder Else If

1 If Else Statement


syntax of if else

Condition specified in if statement is true then the statement associated with if statement are executed otherwise statements of else block is executed.

Java If Else Flowchart
Java If Else Flowchart


Example: Java Program to check values.

we use if else as follows

Java Program to check greater among two values

greater among two variables in java
greater among two variables in java
greater among two variables in java
greater among two variables in java

Output

Q Write a Java Program to compare two Strings

2 If Statement

It is not mandatory to use else with if statement

Syntax of If statement

Example: To print value if is less than 10

Output

This program will not do any thing if number is greater then 10

3 Nested if else in Java

if else statement can be used with in another if else statement.

If or if else inside another if else is known as nesting of if else.

Syntax

Nested If else in Java
Nested If else in Java

Example: Find the greatest among the three numbers.

This is a example of Nested if else.

4 Else if ladder

Syntax

It is the combination of if else if statement Here execution of statement depends upon if statement’s condition.

If the condition is true for if or else if block only its associated statement is executed rest of the condition is not checked.

Ladder if else
Ladder if else

It any condition does not match then else block is executed.

Example: show the grade of student based on percentage in java Programming

This is a good example of If Else Ladder.

5 If Else in short way (Ternary Operator)

We can write if else in short form using ternary operator

Syntax of Ternary operator is as below

variable=(condition)?expression1:expression2

If condition is true then expression1 is executed else expression2 will be executed.

and the result will be stored in variable.

Lets see one example of ternary operator

Example: Find the Greatest among two numbers using ternary operator.

Output

Java If Else Programs

Example: String comparison in If Else

Comparing two string to find is it working day or holiday

Example: Comparing dates in if statements

Output

You can un comment other two value and run to got other if statement executed

Example: Checking Boolean value in if statement

Output

Here we are calling a method in if statement.

This method returns true or false.

based on boolean value it is showing if or else statement.