switch statement

Java Switch Case Example

Photo of Konstantina DimtsaKonstantina DimtsaJanuary 10th, 2014Last Updated: November 9th, 2023
2 1,216 4 minutes read

In this post, we feature a comprehensive Java Switch Case Example. Java provides decision making statements so as to control the flow of your program. The switch statement in java is the one that we will explain in this article. These statements are:

  • if...then
  • if...then...else
  • switch..case
java switch case

A switch statement in java checks if a variable is equal to a list of values. The variable in the switch statement can be abyte, short, int, orchar. However, Java 7 supports alsoswitch statements with Strings. We will see such an example in the next sections.

1. Syntax of Java switch case

The syntax of aswitch case statement is the following:

switch (variable) {  case c1:        statements // they are executed if variable == c1        break;  case c2:         statements // they are executed if variable == c2        break;  case c3:  case c4:                statements // they are executed if variable ==  any of the above c's        break;  . . .  default:        statements // they are executed if none of the above case is satisfied        break;}
  • switch: theswitch keyword is followed by a parenthesized expression, which is tested for equality with the following cases. There is no bound to the number of cases in aswitchstatement.
  • case: thecase keyword is followed by the value to be compared to and a colon. Its value is of the same data type as the variable in theswitch. The case which is equal to the value of the expression is executed.
  • default: If no case value matches theswitch expression value, execution continues at thedefault clause. This is the equivalent of the"else" for theswitch statement. It is conventionally written after the last case, and typically isn’t followed bybreak because execution just continues out of theswitch. However, it would be better to use abreak keyword todefault case, too. If no case matched and there is nodefault clause, execution continues after the end of theswitch statement.
  • break: Thebreak statement causes execution to exit theswitch statement. If there is nobreak, execution flows through into the next case, but generally, this way is not preferred.

2. Example of switch case

Let’s see an example of theswitch case. Create a java class namedSwitchCaseExample.java with the following code:

SwitchCaseExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
packagecom.javacodegeeks.javabasics.switchcase;
 
publicclassSwitchCaseExample {
    publicstaticvoidmain(String[] args) {
 
        grading('A');
        grading('C');
        grading('E');
        grading('G');
    }
 
    publicstaticvoidgrading(chargrade) {
 
        intsuccess;
        switch(grade) {
        case'A':
            System.out.println("Excellent grade");
            success =1;
            break;
        case'B':
            System.out.println("Very good grade");
            success =1;
            break;
        case'C':
            System.out.println("Good grade");
            success =1;
            break;
        case'D':
        case'E':
        case'F':
            System.out.println("Low grade");
            success =0;
            break;
        default:
            System.out.println("Invalid grade");
            success = -1;
            break;
        }
 
        passTheCourse(success);
 
    }
 
    publicstaticvoidpassTheCourse(intsuccess) {
        switch(success) {
        case-1:
            System.out.println("No result");
            break;
        case0:
            System.out.println("Final result: Fail");
            break;
        case1:
            System.out.println("Final result: Success");
            break;
        default:
            System.out.println("Unknown result");
            break;
        }
 
    }
 
}

In the above code we can see twoswitch case statements, one usingchar as data type of the expression of theswitch keyword and one usingint.

Output

Excellent gradeFinal result: SuccessGood gradeFinal result: SuccessLow gradeFinal result: FailInvalid gradeNo result

Below is the equivalent of theswitch case statement in the methodpassTheCourse() usingif..then..else:

1
2
3
4
5
6
7
8
9
if(success == -1) {
        System.out.println("No result");
}elseif(success ==0) {
    System.out.println("Final result: Fail");
}elseif(success ==1) {
    System.out.println("Final result: Success");
}else{
    System.out.println("Unknown result");
}

3. Example of switch case using String

As we mentioned in the introduction of this example, Java SE 7 supports String inswitch case statements. Let’s see such an example. Create a java class namedStringSwitchCase.java with the following code:

StringSwitchCase.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
packagecom.javacodegeeks.javabasics.switchcase;
 
publicclassStringSwitchCase {
     
    publicstaticvoidmain(String args[]) {
         
        visitIsland("Santorini");
        visitIsland("Crete");
        visitIsland("Paros");
         
    }
     
    publicstaticvoidvisitIsland(String island) {
         switch(island) {
          case"Corfu":
               System.out.println("User wants to visit Corfu");
               break;
          case"Crete":
               System.out.println("User wants to visit Crete");
               break;
          case"Santorini":
               System.out.println("User wants to visit Santorini");
               break;
          case"Mykonos":
               System.out.println("User wants to visit Mykonos");
               break;
         default:
               System.out.println("Unknown Island");
               break;
         }
    }
 
}

If we run the above code, we will have the following result:

Output

User wants to visit SantoriniUser wants to visit CreteUnknown Island

4. More articles

5. Download the source code

This was a Java Switch-Case Example.

Download
You can download the source code from here:Java Switch Case Example

Last updated on Apr. 29th, 2021

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Konstantina DimtsaKonstantina DimtsaJanuary 10th, 2014Last Updated: November 9th, 2023
2 1,216 4 minutes read
Photo of Konstantina Dimtsa

Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.