Java if else

Java if else statement is decision making statements. It  checks one or more conditions in program.

Java has the following four conditional statements.

  1.  if statement -  An if statement consists of a boolean expression followed by one or more statements.
  2.  if...else statement - An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
  3. nested if statement - We can use one if or else if statement inside another if or else if statement(s).
  4. switch statement  - We can use switch statement to specify many alternative blocks of code to be executed.

if Statement

We can use if statement to specify a block of code to be executed, if a specified condition is true

Syntax : 

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

if...else statement

We can use else statement to specify a block of code to be executed, if the same condition is false

Syntax : 

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

else if statement

We can use the else if statement to specify a new condition if the first condition is false.

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.
}

 

Using if else staments, we can check usual logical conditions from mathematics as below.

  • Less than: p < q
  • Less than or equal to: p <= q
  • Greater than: p > q
  • Greater than or equal to: p >= q
  • Equal to p == q
  • Not Equal to: p != q

Example :

import java.util.*;

public class Aryatechno {
public static void main(String[] args) {
int marks = 42;
if (marks > 90) {
System.out.println("You got Grade A1 in 10th Exam.");
} else if (marks > 80) {
System.out.println("You got Grade A2 in 10th Exam.");
}else if (marks > 60) {
System.out.println("You got Grade B in 10th Exam.");
} else if (marks > 40) {
System.out.println("You got Grade C in 10th Exam.");
}else {
System.out.println("You failed in 10th Exam.");
}
}
}

Output :

You got Grade C in 10th Exam.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

25589