Decision Making in java


January 4, 2022, Learn eTutorial
1687

In this tutorial, we are going to cover the basics, syntax and uses of Decision Making Statements in java such as if, if else, if else if , nested if etc. Also you will learn how to handle switch  statements in java.

We all used to make decisions in real life. In particular conditions, we prefer the best actions from various choices to achieve the desired result. The concept of decision making in java is also the same. As in any other programming languages, we use the decision-making statements to run the specific block of codes from alternatives to obtain the desired results.

What is decision making?

In definition, Decision Making is the process of choosing a proper course of action from the possible options available for attaining the desired result.

Each programming language has some conditions to control the execution of a program. In java, a decision-making statement provides the selection of statements or blocks of codes to run the programme based on the expressions test conditions. Decision-making structures test one or more conditions in the program. If the value of the expression is true, the flow of control goes into a specific block of codes; otherwise, another set of codes will be executed for the test value; false.

The working of decision-making statements supported by  java is as follows:

DecisionMaking_if

Working of decision-making statements

If the test condition is satisfied, a set of statements is executed, otherwise, a different set of statements is executed. The test condition helps Decision Making in selecting the appropriate set of statements to be executed.

TYPES OF DECISION MAKING STATEMENTS

The following are the various types of Decision Making statements in java that we are going to cover in this tutorial:

  1.  If Statement
    • Simple If statement
    • If-else statement
    • Nested If statement
    • If-else-If statement
  2. Switch Statement

Now let us look at each topic in detail.

1.If statement

An if statement is a powerful tool and simple decision-making statement used to check a specific condition with values. It checks whether the value of the test condition is true or not. It controls the flow of execution of the conditional statements. 

In Java, there are various forms of If statements, and the use of these statements in the program is based on the complexity of the condition to be tested.

Boolean is the data type mostly used in the if statement for conditional testing. Boolean is a primitive data type that only represents the two possible values: true/false. If you haven’t gone through the boolean data type, visit our tutorial of Data types in java.

1.Simple If :

if statement, check the conditions with the two possible values: true/false. If the condition is true, it will execute the block of codes following the body of the condition.
The general syntax of if statements:


If (test_condition)
{
// block of codes();
}
// statement;


The block of code may be a single statement or a group of statements.

Working of if syntax:

Here, if the test condition is true, then the immediate set of codes will be executed; otherwise the control will be skipped to the instruction immediately after the if statement.

Flowchart of If statement:

For more understanding let us see the working in a flowchart:

Fliowchart_if

Flowchart of If statement:

Now see the example of the simple if statement;


public class IfStatementEx {

 public static void main(String[] args) {
  int score = 100;
  if(score==100) {
   System.out.println("Century!!!");
  }
  System.out.println("Exit");
 }
  

Output:


Century!!!
Exit

Program Explanation:

In the program initially, we have assigned an integer value to the variable score. Then using the if statement we check the value in the variable score is 100. If it's equal, then the program should display the message Century!!!. Then it follows the next statement which is again a print statement with the message Exit. If in case the provided condition does not meet, then the statement after the if condition will print, ie, the message Exit will be printed. The downside of a simple if statement is that it only executes the statement following the truth value, True and the False case is not addressed.

2.If-else statement

The working of the If-else statement is similar to the simple if statement. In the if statement, if the test value is false, then the instructions immediately after the If statement will be executed and here in the if-else statement, the else part will be executed when the value of the test condition of if is false.

The syntax of the if-else statement is:


If(test_condition)
{
// block of codes();
}
else
{
// block of codes();
}

 

Working of If-else statement :

Here, if the test condition is true, then the set of codes in the if part will be executed or  if the test condition is false, then the set of codes in the else part will be executed. Thereafter the control will move to the remaining statements.

Fliowchart_if

Flowchart of If-else statement:

Example:


public class IfStatementEx {

 public static void main(String[] args) {
  int n = -10;
  if(n > 0) {
   System.out.println("Positive Number");
  }
  else {
   System.out.println("Negative Number");
  }
  System.out.println("Exit");
 }
 

Output:


Negative Number
Exit

From the above example it is pretty clear that if the given condition n>0 is 

  • True,It should display the message “ Positive Number” as output
  • False,It should display the message “ Negative Number” as output

Here in our case, the value of n is -10 which is a negative number so is the output displayed.

3.If-else-If ladder statements in java

if-else-if ladder can be used to check multiple conditions. It is a very common programming construct that allows checking multiple conditions.

The general syntax is as follows:


If (test_condtion 1)
{
// block of codes();
}
elseIf (test_condtion 2)
{
// block of codes();
}
elseIf (test_condtion 3)
{
// block of codes();
}
 

Working of the If-else-If ladder :

If the test condition is true, the block of code following the test condition will be executed; otherwise the control moves to check the subsequent conditions mentioned in the elseif trails. If none of the conditions are met then the else statement will get executed.

Working flowchart:

Fliowchart_if

Flowchart of If-else-If statement:

Example:



public class IfStatementEx {

 public static void main(String[] args) {
  
  String color = "Red";
  if(color == "Green") {
   System.out.println("GO,PLEASE");
  }
  else if(color =="Orange") {
   System.out.println("WAIT, PLEASE");
  }
  else if(color =="Red"){
   System.out.println("STOP, PLEASE");
    } else {
     System.out.println("Signal not working");
    }
 
 }
}

 

Output:


STOP, PLEASE

The above example shows how a traffic signal works. Here 

  • First we check if the color is Green, if it's true then display the output GO, PLEASE.
  • If not, will again check if the color is Orange, it should display WAIT, PLEASE when the condition is satisfied
  • If not, will again check if the color is Red, if yes the output will be STOP,PLEASE
  • If none of the conditions are met then the else statement will get executed which will print “Signal not working”.
     

4.Nested If

An If inside another if is called a Nested If. Sometimes, we need to check an if statement to execute the target of another If statement.

The general syntax is as follows:


If(test_condition)
{
If(test_condition)
{
// block of codes();
}
Else
{
// block of codes();
}
}
else
{
// block of codes();
}
//statements();

 

Working of syntax :

If the test condition is true, the block of code following the test condition will be executed; Here the block of code is another if statement with else part. If the initial if condition is false then the else statement will get executed.

Working flowchart:

Fliowchart_if

Flowchart of Nested-if statement:

Example:



public class IfStatementEx {

 public static void main(String[] args) {
  
  int a = 10, b =20;
  if(a!=b ) {
   if(a>b) {
    System.out.println("a is greater than b");
   }else {
    System.out.println("a is less than b");
   }
  }else {
   System.out.println("a and b are the same  numbers");
  }
  
 }
}



 

Output:


a is less than b

The above program shows how to validate the relation between two numbers using a nested if. Initially it will check if both numbers are distinct numbers

  • If yes, then it will again check whether the first number a is greater than b or not.
    • If yes , it will display the message “a is greater than b”.
    • If not, it will display the message “a is less than b”.
  • If no, then the program will display the message “ a and b are the same numbers.

2. Switch statement

The switch statement of java is mostly used as a shorthand when we have several choices available to be tested for performing different tasks for each choice. The switch is the shorthand for multiple If statements in java.

The general syntax of the switch case statement is as follows:


Switch(expression);
{
case 0:
Statement 0();
break;
case 1:
Statement1();
break;
case 2:
Statement2();
break;
case 3:
Statement3();
break;
case 4:
Statement4();
break;
default:
Statement details();
}



Working of syntax :

Once the expression given in the switch statement is evaluated ,the value of the expression is compared with the values of each case. The associated block of code will execute when there is a match.The switch statement can be used with or without a break statement and also note that it is mostly used with a break systement.

Fliowchart_if

Flowchart of SWITCH statement:

Checkout the following program:



class Rainbow {
    public static void main(String[] args) {
        int colour = 7;
switch (colour) {
  case 1:
    System.out.println("Red");
    break;
  case 2:
    System.out.println("Orange");
    break;
  case 3:
    System.out.println("Yellow");
    break;
  case 4:
    System.out.println("Green");
    break;
  case 5:
    System.out.println("Blue");
    break;
  case 6:
    System.out.println("Indigo");
    break;
  case 7:
    System.out.println("Violet");
    break;
default:  System.out.println("Not a rainbow colour");
}
 
    }
}


 

Output:


Violet

Here, in this program colour is an integer variable with value 7 assigned to it. Now the switch statement will evaluate the variable and take the value 7 and search for a match in its case values.We have case 7 with a print statement to display “Violet” as its output.

Important points to be taken care of while using the switch statement .

  1. Switch can have one or more number of cases .
  2. The case values should be unique and follow the type of switch expression.
  3. The case value should be either a literal or constant. Variables are not allowed.
  4. Switch expressions can be character, string, integer, byte , short,long or enum.
  5. Keywords break and default are optional.