Decision Statements : Java Switch Statement

java switch case Java Switch Statement

Java switch statement is a way to simulate the use of multiple if else statements in Java. A switch works with different primitive data types like byte, short, char and int. It also works with enumeration and String class as well but for String Java Development Kit version should be above 1.7.

Flow Diagram

java switch case


How Switch Case works

  • Switch statement takes primitive, String and enumeration type values as input.
  • Based on the input values, different cases are checked.
  • If particular case is satisfying the condition, then statement inside that case block will be executed. If break is used as part of statement then rest of the cases will not execute.
  • If none of the case is satisfying the condition then default case will be executed.

Difference between if else and switch case

Switch

If Else

Switch is faster than then if else statement.

If else is slow compared to switch.

Switch does not allow float and double values

You can operate if else with float and double

In if else, control goes through each and every if else statement until it finds the true value.

But in case of switch control directly goes to the appropriate case.

Switch statement is more readable.

If else becomes difficult as the number of case increases.

Switch case internally uses equality operator.

If else checks true or false values.

Switch statements can be optimized.

It is difficult to optimize if else ladder.



An Example

Let’s create a simple switch example as below.

public class SwitchExample {

 public static void main(String[] args) {

 char erroCode = 'E';

 switch (erroCode) {

 case 'E':
 System.out.println("Remote machine retured System error.");
 break;
 case 'A':
 System.out.println("Remote machine retured API error.");
 break;
 default:
 System.out.println("Unkown error retured from Remote Machine.");

 }

 }

}

Note*: If you don’t use “break” inside each case then every case will be executed. So it is important to understand the use of break in switch statement.

In this example, we have created a char variable with which takes error code as character value. Based on the error code output message will be generated.

Leave a Reply

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