Decision Making

There are two types of decision making statements in Java. They are as follows
  1. if statements
  2. switch statements
Decision Making in Java

1) if Statement
  • if statement consists of a Boolean expression followed by one or more statements.
  • If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If not, control jumps to next line outside if loop
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Test {

 public static void main(String args[]) {

  int x = 10;
  if (x < 20) {
   System.out.print("This is if statement");
  }
 }
}

Output:
This is if statement

2) if...else Statement
if statement can be followed by an optional else statement, which executes when the condition mentioned is false.

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Test {

 public static void main(String args[]) {

  int x = 30;

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

Output:
This is else statement

3) if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Test {

 public static void main(String args[]) {

  int x = 30;

  if (x == 10) {
   System.out.print("Value of X is 10");
  } else if (x == 20) {
   System.out.print("Value of X is 20");
  } else if (x == 30) {
   System.out.print("Value of X is 30");
  } else {
   System.out.print("This is else statement");
  }
 }
}

Output:
Value of X is 30

4) switch statement
A switch statement allows a variable to be tested against a list of values. Each value is called a case and the variable is being checked for each case.

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Test {

 public static void main(String args[]) {

  char grade = "D";

  switch (grade){
  
  case 'A':
   System.out.println("Excellent!");
   break;

  case 'B':

  case 'C':
   System.out.println("Well done");
   break;

  case 'D':
   System.out.println("You passed");

  case 'F':
   System.out.println("Better try again");
   break;

  default:
   System.out.println("Invalid grade");
  }
 }
}

Output:
You passed


<-- Previous || Next -->

No comments:

Post a Comment