- Java provides IF conditional statements for executing statements based on some condition
- It can be used to take decision and follow certain execution path conditionally
- It has the following form:
if (condition)
statement(s);
else
statement(s);
- Condition may be any logical or relational expression that returns a Boolean value.
- If condition is true it returns true value otherwise false
- Statement may be a single statement or a block of statements enclosed within a curly braces
- At very first condition is checked.
- If condition is true then true block of statements is executed and if condition is false, false block will be executed
- In every case only one block of statement will be executed
- For example:
if(X>Y)
System.out.println(“X is greater”);
else
System.out.println(“Y is greater”);
- We can also place one if statement inside another if statement.
- When one if statement appears inside the another if statement, it is called Nested IF
- For example:
if (i==10)
{
if (j<20)
a=b;
else
a=c;
}
else
{
a=d;
}
If Else Ladder
- if else ladder is a series of simple if…else statements
- It can be used to select single choice among multiple options
- Condition will be checked from the top to the bottom
- If condition is true, it will execute statements associated with that if otherwise next if will be checked
- Finally, if no condition evaluates to true then default else part will be executed but if there is no final else part then no action will be take place
- It has the following form:
if (condition1)
statement(s)1;
else if (condition2)
statement(s)2;
...
...
else
statement(s);