Java - Decision Control and looping statement - If-else Tutorial
Java if-else statement is used to check the condition whether it is true or false. If the first condition is false then it will check the next condition, if the next condition also false, then it will finally run the else condition.
- If statement
It executes if block only when if condition is true.
public class Ifcondition{
public static void main(String args[]){
int x=5;
if(x<6){
System.out.println("x is smaller than 6");
}
if(x<3){
System.out.println("x is smaller than 3");
}
}}
Output -
x is smaller than 6
- If-else statement
It checks first for if condition, if the condition is true, it will execute if block, else it will execute else block.
public class Ifelsecondition{
public static void main(String args[]){
int x=5;
if(x>6){
System.out.println("x is greater than 6");
}
else{
System.out.println("x is smaller than 6");
}
}}
Output -
x is smaller than 6
- If-else-if ladder
It checks first for if condition, if the condition is true, it will execute if block, otherwise it will go to next condition i.e else if.
If the condition went false, it will again move toward next else if condition, still the condition becomes true.
At last, if no condition is satisfied, finally it will execute else block.
public class Ifelsecondition{
public static void main(String args[]){
int x=6;
if(x>6){
System.out.println("x is greater than 6");
}
else if(x==6){
System.out.println("x is equal to 6");
}
else{
System.out.println("x is less than 6");
}
}}
Output -
x is equal to 6