.


Divya

Java if else statement


If statement is a control statement. The body of the if statement is executed when condition is true or nonzero and if the condition is false then the else part is execute.

It checks boolean condition: true or false.

There are various type of if statement in Java:

  • if-else statement
  • if-else-if ladder
  • nested if statement
  • if statement

If statement

It is used to check the condition is true or false.If the condition is true then the body of the if statement is executed.

Syntax:

if (condition) {
    block of code to be executed if the condition is true
}

Example

public class IfExample {
public static void main(String[] args) {
int a=20;
int b=10;
if(a>b){
System.out.print("a is greater than b");
}
}
}

Output : a is greater than b

If else statement

The Java if else condition is also used to check the condition.But the only difference between Java if statement and Java if else statement there is no else part in if statement.

In Java if else condition it first check the condition , if the condition is false then it execute the code.

Syntax:

if (condition) {
    block of code to be executed if the condition is true
} else {
    code to be executed if the condition is false
}

Example

public class IfelseExample {
public static void main(String[] args) {
int a=20;
int b=10;
if(a>b){
System.out.print("a is greater than b");
}
Else{
System.out.print("b is greater than a");
}
}
}

Output : a is greater than b

Java if-else-if ladder Statement

In java if else statement we only write two condition(Either false or true) but in if-else-if ladder Statement we executes different codes for more than two conditions.

Syntax

if (condition1) {
    block of code to be executed if condition1 is true
} else if (condition2) {
    block of code to be executed if the condition1 is false and condition2 is true
} else {
    block of code to be executed if the condition1 is false and condition2 is false
}

Example

public class if-else-if ladderExample {
public static void main(String[] args) {
int a=50; if(a<50){
System.out.println("Back");
}
else if(a>=40 && a<50){
System.out.println("D grade");
}
else if(a>=50 && a<60){
System.out.println("C grade");
}
else if(a>=60 && a <70){
System.out.println("B grade");
}
else if(a>=70 && a<80){
System.out.println("A grade");
}
else if(a>=80 && a<90){
System.out.println("E grade");
}else if(a>=90 && a<100){
System.out.println("O grade");
}else{
System.out.println("Invalid!");
}
}
}

Output : C grade



.