JAVA- if statement

The if statement is use to control the flow of the execution of statement. If the expression is true then it transfers the control to the particular statement.

There are different forms of if statements, these are as followings:

A.     simple if statement:

Syntax:

if(expression)

{                    //statement block

Statement-A;

}

Statement-B;

There may b more than one statement in a block. If the expression is true then the statement-A will be execute, otherwise it skips the statement and will jump to the statement-B. if statement-A will be executed after that statement-B will executed in a sequence.

B.      If-else statement:

Syntax:

if(expression)

{

True-block

}

else

{

False-block

}

If the condition is true at first then the true block will be executed else false block will be executed.

C.      Nesting of if-else statements:

Syntax:           

if(condition-1)

{

If(condition-2)

{

Statement-1;

}

else

{

Statement-2;

}

}

else

{

Statement-3;

}

In this if the condition-1 is true then it will check the condition-2 and if it true then statement-1

will be executed else it will executes the statement-2. And if the condition-1 is fail then the

control will goes to the else part and will executes the statement-3.

D.     The else-if ladder:

Syntax:

if(condition-1)

Statement-1;

else if(condition-2)

statement-2;

else if(condition-3)

statement-3;

else if(condition n)

statement-n;

else

default-statement;

statement-z;

Here we can see in above syntax how else-if ladder is working. If any of condition is true then it will execute that statement and will skip the rest of conditions and the control will goes to the statement-z. If any of the condition is not true then the default-statement in else part will be executed and then as in sequence the statement-z.

Leave a Reply

Your email address will not be published. Required fields are marked *