Decision Making In Java Using If, Else-If And Switch Statements | Part 1

Decision Making In Java Using If, Else-If And Switch Statements | Part 1
Decision Making In Java Using If, Else-If And Switch Statements | Part 1

Introduction

Life is all about making choices. There isn’t a single day that goes by when we don’t have to make a decision. 

Some decisions are completely spontaneous and require no thought at all. People do not dwell on decisions such as what to wear to work, what to eat for lunch, or which route to take to work.

Whereas some are significant and have the potential to change the course of your life. For example, what platform should you use to learn Data Structures and Algorithms, or where should you practise interview questions?

Choosing from the available options is essentially what decision-making is all about. The better your choices, the better your decision-making. In programming, we face similar scenarios where we must make decisions and then execute the next block of code based on those decisions.

We have various decision-making statements to deal with these scenarios, but first, let’s define a decision-making statement before we get into those.

What is a Decision-making statement?

Decision making in Java is an essential aspect of learning Java. It allows a program to select multiple execution paths based on the result of an expression or the value of a variable. For a beginner in programming, decision making is considered the first milestone to achieve.

Decision making in Java is divided into the following categories: 

  • Selection statements: allow to choose different paths of execution.
  • Jump statements: enables a program to execute in a nonlinear fashion.

This article primarily focuses on the selection statements such as if-else, nested if-else, and switch. Jump statements in Java such as break and continue are covered in the second blog of this series Decision making in Java using Jump Statements | Part 2.  

To get a clear understanding of Java’s decision-making, we recommend you read both the articles in this series.

Selection Statements in Java

Java supports two types of selection statements: if and switch. These statements allow us to regulate the flow of our program’s execution. 

blog banner 1

These two statements have a lot of power and versatility. Let’s dig deeper into these statements one by one.

If and else Statement

The if statement in Java is a conditional branch statement. It can be used to direct the execution of a program into two different routes. Here’s the general form of the if statement:

if (condition) {
	statement1; 
}
else {
	statement2;
}

In the above code,

  • Condition is an expression that results in a boolean value.
  • Else clause is optional.
  • Each statement can be a single statement or a block of statements enclosed in curly braces.

The if statement functions as follows: If the condition is true, statement1 will be executed. If not, statement2 will be executed (if it is present). Both statements will never be executed.

Flowchart for the if-else statement

For example, In the following code, if a is less than b, then a is set to zero. Otherwise, b is set to zero. Both a and b will never be set to zero simultaneously.

public class Test
{
    int a, b;

    if(a < b) 
          a = 0; 
    else 
          b = 0;
}

Some of the essential points regarding if statements are:

1. Most often, the expression used inside if involves the relational operators. However, that is not necessary. It is possible to control the if statement using a boolean variable.

For example, the if block is taking a value rather than an expression having a relational operator in the program below.

public class Test {
	public static void main(String args[])
    {
			boolean val = false;
			int counter;
			 if (val)
				 counter = 1; //one statement 
			else
				counter = 0;  //one statement
        System.out.println("The counter is having a value: "+counter);
    }
}

Output:
The counter is having a value: 0

2. After the if or else, only one statement can be placed directly under it. To include more statements, we need to create a block of statements. Curly brackets will enclose this block.

For example, In the following program, the if and else block has more than one statement inside it. That’s why the statements are enclosed in curly braces.

import java.util.Scanner;
public class Test {
	public static void main(String args[])
    {
		int flag =0;
		Scanner s = new Scanner(System.in);	
		System.out.println("Enter two numbers");
		int a = s.nextInt();
		int b = s.nextInt();
			if (a > b)
			 {
				 flag = a;
				 System.out.println("The greater value is: "+flag);
				 return;
			 }
			else
			{
				flag = b;
				System.out.println("The greater value is: "+flag);
				return;
			}
    }
}

Output:
Enter two numbers
12
34
The greater value is: 34

Nested if-else statement

An if-else statement within an if-else statement is known as a nested if-else. Nested ifs are very common in programming. The main thing here is that an else statement always refers to the nearest if statement within the same block. 

For Example:

if(i == 10) // top-most if
{
if(j < 20)// first nested if
a = b;
{
if(k > 100) // second nested if
c = d; 
else // inner else
a = c; 
	}
}
else // final else
a = d; // this else refers to the top-most if

As the comments indicate, the final else is not associated with the first nested if. Instead, the final else is associated with the top-most if. The inner else is associated with the second nested if because it is the closest within the same block.

Flowchart for Nested If-else statements

if-else-if ladder

The if-else-if ladder is a common programming construct that is based on a series of nested ifs. An if else-if ladder looks like this:

if(condition) 
statement; 
else if(condition) 
statement; 
else if(condition) 
statement; 
.
.
.
else 
statement;

The else-if ladder is executed from top to bottom. As soon as one of the conditions becomes true, the program executes the statement associated with it. If none of the conditions holds, it will execute the final else statement.

Flowchart for if else-if ladder

Here is a program that uses an if-else-if ladder to determine which months are associated with certain seasons.

public class IfElse 
{ 
    public static void main(String args[]) 
    { 
    int month = 4; // April Spring season;
 
    if(month == 12 || month == 1 || month == 2) 
        season = "Winter"; 

    else if(month == 3 || month == 4 || month == 5) 
        season = "Spring"; 

    else if(month == 6 || month == 7 || month == 8) 
        season = "Summer"; 

    else if(month == 9 || month == 10 || month == 11) 
        season = "Autumn"; 

    else 
        season = "No"; 

System.out.println("The " + season + " season is there in April."); 
    }
 } 

When you run the program with month=4 as input, the output will be: The Winter season is there in April. So far, we have discussed decision making statements like If-else, Nested if-else, If else-if ladder. 

Are you worrying about crowded if-else statements? Now let’s move on to an effective alternative for these if-else decision making statements in Java.

Switch Case

The multiway branch statement in Java is known as the switch statement. The switch statement makes it simple to redirect execution to different parts of code depending on the value of an expression. 

As a result, using the switch statement is typically a better option than a long series of if-else-if statements. The generalised form of a switch statement is given below:

switch (expression) {
case value1:
    // statement sequence
    break;
case value2:
    // statement sequence
    break;
.
.
.
case valueN:
    // statement sequence
    break;
default:
    // default statement sequence
}

Some of the essential points regarding the switch statements are:

  • The expression should be of type byte, short, int, or char only. 
  • An enumeration can also be used to control a switch statement. 
  • The values provided in the cases must be compatible with the switch expression. 
  • Each case value must be constant. 
  • Duplicate case values are not allowed.

The switch case works in the following way:

The expression is compared with every literal value of the case clause inside the switch block. If a match is found, the code inside that case will be executed. If none of the cases matches the value of the expression, then the default statement is executed. However, the default case is optional. If no case matches the expression and the default case is absent, nothing will happen.

The break statement is used with the switch statement to terminate a case statement. 

  • This helps in “jumping out” of the switch when a case clause is executed. 
  • The break statement is optional. If we omit the break statement, execution will continue into the next case.
  • Multiple cases with no break statements between them are sometimes needed.

Flowchart for Switch Case in Java

Image Source: Techcrashcourse

Nested Switch Statements

A switch can also be used inside a case statement. This is referred to as a nested switch. Since a switch statement creates its own block, no conflict will arise between both the switch statements.

The following program shows an example of a nested switch:

switch(count1) // outer switch
{ 
case 1: 
switch(target) // inner switch
{ 	
// nested switch 
case 0: 
System.out.println("target is zero"); 
break;
case 1: 
System.out.println("target is one"); 
break; 
} 
// no conflicts with outer switch 
break; 
case 2: 
// and so on…

Here, the statements in the inner switch do not conflict with the statements in the outer switch. The count1 variable is only compared with the cases of the outer switch. If the value of count1 is 1, then the target is compared with the inner switch cases.

There is an interesting point regarding switch statements, and it gives a clear insight into how the Java compiler works. The Java compiler builds a “jump table” for each case when it compiles a switch statement. This table is used to determine the execution path based on the expression’s value.

As a result, if you need to choose from a large number of options, a switch statement will be substantially faster than a series of if-else statements.

Champ If you’ve made it this far, we recommend you try your hand at the Decision Making in Java problems. Earn points here to boost your confidence.

Also, if you haven’t discovered the benefits of Guided Path yet, go there once, and there will be no turning back.

Frequently Asked Questions

What is decision making in Java?

Decision making in Java allows a program to select multiple execution paths based on the result of an expression or the value of a variable.

What are the statements used in decision making in Java?

The decision-making statements used in Java are if-else and switch statements.

Are if-else statements faster than switch?

No, the execution of the switch statement is faster, as explained above.

When should we use a switch case?

When you have to compare multiple possible conditions of an expression and the expression itself is non-trivial.

What is a nested switch statement?

Nested Switch Statements occur when a switch statement is defined inside another switch statement.

Key Takeaways

This blog answers all the questions that are related to selection statements in Java. From nested if-else statements to nested switch cases, it explains everything. 

Decision-making in Java also includes jump statements such as break and continue. To complete learning this topic, let’s move on to the second blog on this series: Decision making in Java using  Jump Statements | Part 2.

Happy Learning!

By Vaishnavi Pandey