Learning Switch Statement in Java Programming

Welcome to our next Java lesson and in this lesson we are going to learn about the switch statement.

What is a switch statement?

A switch statement is just like if else if statement the difference is that there is only one expression/variable to be tested in switch statement.

Here’s the syntax of the switch statement:

switch (variableToTest) {

  case Value1:

        statement(s) to be executed if  variableToTest = Value1;
        break;

  case Value2:

        statement(s) to be executed if  variableToTest = Value2;
        break;

  case Value3:

        statement(s) to be executed if  variableToTest = Value3;
        break;

  default:

        statement(s) to be executed if  all cases did not match the variableToTest;
        break;

}

Where:

variableToTest is the variable  to be compared to the case values.

 case Value:

        statement(s) to be executed if  variableToTest = Value;
        break;

This is an example of a case group; Value must be equal to the value of the variable to be tested so that the case with the same value as the variable will be executed. You can create as many case groups as you want.

break statement will end the execution of each case of the switch statement.

default if no case value matches the value of the variable, then it will jump to the default clause and execute its statement(s). It is just like the else in the if else if statement and it is written after the last case group.

Note: The expression or variable must be an int, short, byte, or char. It can’t be a long or a floating-point type.

Example:

import java.util.*;

class switchStatement{

static Scanner console = new Scanner(System.in);

public static void main(String[] args){

int score;

System.out.print("Enter your score:");

score = console.nextInt();

switch (score){

case 100:

System.out.print("you've got the perfect score");
break;

case 88:

System.out.print("you've got the average score");
break;

case 75:

System.out.print("you've got the passing score");
break;

default:

System.out.print("please enter another score");
break;

}

}
}

The scenario in the above example was taken in the Java if statement of the previous lesson. We have just converted it to switch statement.

The program will asked you to enter a score, then the value entered by the user will be the value of our score variable, the switch statement will then match the score variable to the case value, if it finds a match then the statements under that case will be executed and if it there’s no match the program will jump to the default clause and exits the switch statement.

Note: you cannot have the same case value, the compiler will detect it and prompt you with an error saying that duplicate case level.

, ,

Post navigation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.