If statement is very powerful decision making statement and is used to control the flow of execution of statement .
If we want to execute a statement on some condition . than we should use the if statement
Syntax :-
If(Condition){
//Statement
}
Example :-
If(a<b){
System.out.println(a is smaller than b);
}
In above example first it check that if a is less than b only if it is true then next statement will be executed otherwise no statement will be executed.
If statement can be implemented in the following ways:-
1. Simple if statement
2. If else statement
3. Else if ladder
4. Nested if else statement
1) Simple if statement :-
If (condition){
Statement - block - x
}
Statement –block – y
In this is if the condition is true then statement block x will be executed and then statement block y will be executed, otherwise the statement block x will be skipped only statement block y will be executed.
Example :
Class SimpleIf{
Public static void main(String args[]){
Int a=10,b=5;
If(a>b){
System.out.println(“a is greater”);
}
System.out.println(“Thanks for coming”);
}
}
Output:
a is greater
Thanks for coming
IF Else statement:-
If(condition)
{
Statement – block -x
}
else
{
Statement – block – y
}
Statement-z
In this if the condition is true then statement block x will be executed and statement block y will be skipped and then statement z will be executed and condition will false then statement block x will be skipped and statement block y will be executed and statement z will be executed.
Nested if else:-
If(condition 1){
If(condition 2){
Statement -1
}
else{
statement - 2
}
}
else{
statement -3
}
In the above example if condition-1 is false then statement -1 and statement-2 will be skipped and only statement -3 will be executed and if the condition -1 will true then condition-2 will be checked and if condition -2 will be true then statement -1 will be executed otherwise statement -2 will be executed.
Example
Int a=5;
Int b=10;
Int c=15;
If(a>b){
If(a>c){
System.out.println(“a is greater”);
}
else{
System.out.println(“c is greater”)
}
}
else{
if(b>c){
System.out.println(“b is greater”);
}
else{
System.out.println(“c is greater”);
}
}
Else if ladder:- If we want to use multiple decision in our program then we have an another option that is else if ladder.
Syntax:
If(condition 1) {
Statement 1
}
else if(condition 2){
Statement 2
}
else if(condition 2){
Statement 2
}
else{
Statement 3
}
In this all the condition is evaluated from top to down which condition is that statement will be executed if all condition will be false then final else statement will be executed.
Example
If(marks>90){
System.out.println(“First division”)
}
else If(marks>80){
System.out.println(“Second division”)
}
else If(marks>60){
System.out.println(“Third division”)
}
else {
System.out.println(“Pass”)
}
This will end our if statement