Java – If Selection Statements

Home/Java - Tutorial/Java - Control Statements/Java – If Selection Statements
Java – If Selection Statements 2017-06-13T10:02:20+00:00

if else if in java:

The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths.
Syntax :
if (condition)
{
     statement1;
}
When the condition is true the Statement within the if is executed. After that execution continues with the next statement after the if statement.
 If the condition is false then the statement within the if is not executed and the execution continues with the statement after the if statement.

EX.



 


Output :
    Largest number = 20
NOTE : The number of statement in if block is only one than parentheses are optional but if its more than one than parentheses are compulsury. And if we enter the same value in x1, x2 and x3 in above program than largest number is x1 because our both condition will be false because here we checked only > not >=.
EX.
if (condition)
{
Statement 1;
Statement 2;
}
Same as above, except that here multiple statements are executed if the condition Is true.

if else :

Syntax :

if (condition)
{
    statement1;
}
else
{
    statement2;
}
The if else work like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 is executed. In no case will both statements be executed.


 


Output :
The student has passed ..
NOTE : As above here also we can put multiple statements in if and else block.

if-else-if Ladder :

Syntax :

if(condition)
  statements;
else if(condition)
  statemenst;
else if(condition)
  statements;
else
  statements;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed.
If there is no final else and all other conditions are false, then no action will take place.
EX.


 


Output :
Tuesday

Nested if :

A nested if is an if statement that is the target of another if or else.
Nested ifs are very common in programming.
Syntax :
if(condition)
{
     if(condition)
         statements….
     else
         statements….
}
else
{
      if(condition)
         statements….
     else
         statements….
}
EX.


 


Output :
max value = 15

Prev Next