Conditional Statements( if/else ) in Java

Conditional Statements
The conditional statement in Java has the form
1 ) If  statement
It is used to decide whether an action is to be performed based on a condition. The given condition is true then block of statement will be executed.
if (<conditional expression>) 
{
<statement1>
<Statement2>
}
The condition must be surrounded by parentheses.
For example:
int yourMarks; if (yourMarks >= 30) { result= "Pass"; }
In this code all the statements surrounded by the braces will be executed when yourMarks is greater than or equal to 30.
2 ) If/else  statement
It is used to decide whether an action is to be performed based on a condition. The given condition is true then block of  if statement will be executed otherwise else block of statement will be executed .
Syntax:

if (<conditional expression>) 
{
<statement1>
}

else 
{
<Statement2>
}

For example:
int yourMarks; if (yourMarks >= 30) { result= "Pass"; } else { result="Fail" }
3 ) If-else-if Ladder statement
Syntax

if (<conditional expression>) 
{
<statement1>
}

else if (<conditional expression>) 
{
<Statement2>
}

else
{
<statement3>
}

For example:
int yourMarks; if (yourMarks >= 30 && yourMarks<45) { result= "Pass"; } else if(yourMarks>=45 && yourMarks <60) { result="Satisfactory"; } else if(yourMarks>=60) { result="Excellent"; } else { result="Fail" }
 



 

Latest Tutorial


Most Visited Tutorial