Java if-else Statement: Syntax and Usage Explained

Rumman Ansari   Software Engineer   2024-07-04 03:28:18   7262  Share
Subject Syllabus DetailsSubject Details 4 Program
☰ TContent
☰Fullscreen

Table of Content:

if-else examples in java

Example 1: if-else statement

public class IfExample {
public static void main(String[] args) {
    int x = 18;

      if( x < 20 ) {
         System.out.println("This is if statement");
      }else {
         System.out.println("This is else statement");
      }

  }
}

This is if statement
Press any key to continue . . .

Example 2: if-else statement

public class IfExample {
public static void main(String[] args) {
    int x = 23;

      if( x < 20 ) {
         System.out.println("This is if statement");
      }else {
         System.out.println("This is else statement");
      }

  }
}

This is else statement
Press any key to continue . . .

Example 3: if-else statement

public class IfExample {
public static void main(String[] args) {
	int number = 10;
    if (number %  2 == 0 )
	System.out.println(number +  " is even." );
	else
    System.out.println(number +  " is odd." );

  }
}

10 is even.
Press any key to continue . . .

Example 4: if-else statement

public class IfExample {
public static void main(String[] args) {
	int number = 11;
    if (number %  2 == 0 )
	System.out.println(number +  " is even." );
	else
    System.out.println(number +  " is odd." );

  }
}

11 is odd.
Press any key to continue . . .

Example 4: if-else statement

public class IfElseExample {
public static void main(String[] args) {
     int marks = 85;
        String grade;

        if (marks >= 35) {
            grade = "Pass";
        }
        else
        {
            grade = "Fail";
        }

        System.out.println("Grade = " + grade);
  }
}

Grade = Pass
Press any key to continue . . .