Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Java If-else


The Java if statement is used to test the condition. It returns true or false. There are various types of if statement in java.

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

Java IF Statement

The if statement tests the condition. It executes the if statement if condition is true.

Syntax:

  1. if(condition){
  2. //code to be executed
  3. }

if1

Example:

  1. public class IfExample {
  2. public static void main(String[] args) {
  3.     int age=20;
  4.     if(age>18){
  5.         System.out.print(“Age is greater than 18”);
  6.     }
  7. }
  8. }

Output:

Age is greater than 18

Java IF-else Statement

The if-else statement also tests the condition. It executes the if block if condition is true otherwise else block.

Syntax:

  1. if(condition){
  2. //code if condition is true
  3. }else{
  4. //code if condition is false
  5. }

if2

Example:

  1. public class IfElseExample {
  2. public static void main(String[] args) {
  3.     int number=13;
  4.     if(number%2==0){
  5.         System.out.println(“even number”);
  6.     }else{
  7.         System.out.println(“odd number”);
  8.     }
  9. }
  10. }

Output:

odd number

Java IF-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

  1. if(condition1){
  2. //code to be executed if condition1 is true
  3. }else if(condition2){
  4. //code to be executed if condition2 is true
  5. }
  6. else if(condition3){
  7. //code to be executed if condition3 is true
  8. }
  9. else{
  10. //code to be executed if all the conditions are false
  11. }

elseifladder

Example:

  1. public class IfElseIfExample {
  2. public static void main(String[] args) {
  3.     int marks=65;
  4.     if(marks<50){
  5.         System.out.println(“fail”);
  6.     }
  7.     else if(marks>=50 && marks<60){
  8.         System.out.println(“D grade”);
  9.     }
  10.     else if(marks>=60 && marks<70){
  11.         System.out.println(“C grade”);
  12.     }
  13.     else if(marks>=70 && marks<80){
  14.         System.out.println(“B grade”);
  15.     }
  16.     else if(marks>=80 && marks<90){
  17.         System.out.println(“A grade”);
  18.     }else if(marks>=90 && marks<100){
  19.         System.out.println(“A+ grade”);
  20.     }else{
  21.         System.out.println(“Invalid!”);
  22.     }
  23. }
  24. }

Output:

C grade

Comments

comments