Java – If Then Else Statement

PREV     NEXT

If then else statement provides two paths. The if block is executed when the condition holds true. When the condition evaluates to false, the statements inside the else block are executed.

Syntax:

if(condition)

{ //statements, when condition is true


}

else

{


//statements, when condition is false

}

Example:

COMPILE & RUN

Output:

b is greater than a

In the above program, the statement inside the else block is executed since the condition a>b evaluates to false.

Else if statement:

We can also provide multiple conditions to be checked by using else if statement.

Example:

COMPILE & RUN

Output:

First class

In the above program, the top most ‘if’ condition evaluates to ‘true’ and its statements are executed. Since this is evaluated to true, control will not go to check other else if conditions and last else block. otherwise the control keeps on shifting to the next else-if loop till any of its condition holds true. The last else block executes only when the if block and all the else-if blocks fails to execute.

PREV     NEXT

Share this website !!!
Facebook Twitter Linkedin