The if-else Statement in Java
These are condition(branching) blocks. The "if-else" are the basic building blocks of any programming language for branching statements.
if-statement
The "if" is a Single-Selection Statement in itself.
The conditional statement in Java has the syntax as,
The conditional statement in Java has the syntax as,
if (condition) statement
The condition must be surrounded by parentheses.
if-else statement
There are two possible paths of execution in the if-else statement. The path is selected upon the basis of the condition expression.for example,
if( studentGrade>=60) System.out.println(“Passed”); else System.out.println(“Failed”);
if-else ladder
Multiple selection paths are available in the if-else-if ladder. The path will be selected upon the basis of the condition expression.
For example,
public class Demo { public static void main(String[] args) { int marks=90; if(marks>=90)//condition-1 { System.out.println("you have done excellent!!!"); }else if(marks>=75 && marks<90)//condition-2 { System.out.println("you have done very good!!!"); }else if(marks>=60 && marks<75)//condition-3 { System.out.println("you have done fair!!!"); }else if(marks>=50 && marks<60)//condition-4 { System.out.println("you have done satisfactory!!!"); } else//otherwise { System.out.println("Try again!!!"); } } }
Nested if-else Statements
A Java program can test multiple cases by placing if...else statements inside other if...else statements to create nested if...else statements. For example, the following pseudo-code represents a nested if...else that prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades:
for example:
if ( studentGrade >= 90 )
System.out.println( "A" );
else
if ( studentGrade >= 80 )
System.out.println( "B" );
else
if ( studentGrade >= 70 )
System.out.println( "C" );
else
if ( studentGrade >= 60 )
System.out.println( "D" );
else
System.out.println( "F" );