$show=/label

Java Switch Statement

SHARE:

A detailed tutorial about the Switch statement in Java and its evolution over time. Java-W3schools blog. All cases of Switch Statement in Java 8 with interview Questions.



In this tutorial, We will learn switch statement.
Switch statement is similar to If else statement. If and If-Else statements can be used to support both simple and complex decision logic. In many cases, the switch statement provides a cleaner way to handle complex decision(business) logic.
switch statements depends on the expression "matching" or being "equal" to one of the cases.


We will learn 1) Switch Statement, syntax, example
2) Default case
3) Java 8 Switch statement
4) Break and Fall down/through switch statement

Read more about "If, If Else, nested Condition - Statement in java".

Switch Syntax:

switch ( expression ) { 
    // expression is an variable name
    // case statements. 
    // If any expression value is matched to the any case constant value then that piece of code will be executed.
    case constant_value_1: 
        // some code here
    case constant__value_2: 
        // some code here
    default: default block of code
}

Flow Chart:

Java Switch Statement


Interview Questions:

Can expression be what data types accept?
What is the use of default case?
Should we use break statement in every case?
Is break statement is optional?
If expression value is not matched constants in case?
If we remove the break statement then what will happen?
If we remove the break statements in all cases then what will happen?
Can we remove the default case?
Shall we use String as expression?
Is legal to use same constant in two cases?
Can we pass Wrapper class instance to switch?
Can we pass a variable to case ? (Eg. int number=100, case number;)
Can we use final on case constants?
Can we use default case in middle of cases?
Can we write code after break statement?


Switch Example:


package com.adeepdrive.switchdemo;
public class SwithExample {
   public static void main(String[] args) {
        int day = 3;
        String dayInWeek;
        switch (day) {
        case 1:
            dayInWeek = "Monday";
            break;
        case 2:
            dayInWeek = "Tuesday";
            break;
        case 3:
           dayInWeek = "Wednesday";
            break;
        case 4:
            dayInWeek = "Thursday";
            break;
        case 5:
            dayInWeek = "Friday";
            break;
        case 6:
            dayInWeek = "Saturday";
            break;
        case 7:
            dayInWeek = "Sunday";
            break;
        default:
            dayInWeek = "Invalid day";
            break;
        }
        System.out.println("Given day is : " + dayInWeek);
    }
}

Output:

Given day is : Wednesday



Thumb rules:


1. A switch's expression must evaluate to a
   char
   byte
   short
   int
   an enum (Added in Java 5)
   String (Added in Java 7)

2. char, byte, short are implicitly promoted to int.
3. Case constant type must be same as switch expression.
4. Case constant must be resolved at compile time because it is a compile time constant.
5. Keyword final can be used in case constant.
6. Case constants are case sensitive. Eg. 'a' and 'A' are considered as two different constants.

Illegal rules:

Remaining primitive types are not allowed to use in switch expression. They are
long
double
float

Default case:

Default case is similar to the else block in if-else. If any of the cases are not matching then default case block will be executed.

The below example to check the given number is even or odd in first 10 numbers. Do not worry about continuous case statements. We will be discussing soon in this post.

        int x = 5;
        switch (x) {
        case 2:
        case 4:
        case 6:
        case 8:
        case 10: {
            System.out.println("x is an even number");
            break;
        }
        default:
           System.out.println("x is an odd number");
        }
Output:

x is an odd number

Because x value is 5 which is not matched to the any case in it. So, it falls in default case.
       

Keyword Final in Switch:


    char status = 1;
        String statusString;
        final char statusA = 'A';
        switch (status) {
        case statusA:
            statusString = "Accepted";
            break;
        case 'P':
            statusString = "Processing";
            break;
        default:
            statusString = "Error occured";
        }
    System.out.println("final switch example : "+statusString);
   
Output:

final switch example : Error occured

Illegal case constant:

Now change the above code as below and it's become illegal. If the varaible is final.

char statusA = 'A';
       
case statusA: --> compile time error.
    statusString = "Accepted";
    break;

Output:

compile time error: case expressions must be constant expressions. Here statusA is a normal variable which can be changed but not constant. If it is final, then no issues.

Final variable must be initialized otherwise compile time error.

final char statusA;
    switch (status) {
        case statusA: --> compile time error.
            statusString = "Accepted";
            break;

Output:
The local variable statusA may not have been initialized

Next, Out of range in Switch:

If we use large value than it's expression data type then we will get compile time error.
Second case constant value is 128 which is out of range of byte.

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

byte g = 2;
switch(g) {
case 23:
case 128: // compile time error.
}

Output:

possible loss of precision
found : int
required: byte
case 128

g variable type is byte, case constant values also should be in byte range. but, 2nd case value is 128. It's is out of range of byte type.

Duplicate case statements:

int percentage = 90;
switch(percentage) {
case 80 : System.out.println("80%"); break;
case 80 : System.out.println("80%"); break; // won't compile!
case 90 : System.out.println("90%"); break;
default : System.out.println("default");
}

Output:

Compile time error: Duplicate case

Wrapper class in Switch:


switch(new Integer(75)) {
case 74: System.out.println("75% marks. boxing is OK"); break;
default: System.out.println("default case");
}

Output:
75% marks. boxing is OK

Break and Fall-Through in switch:

break statement is used in switch is to come out from case block. If do not use break in all cases then what will happen.

        int day = 1;
        String dayInWeek;
        switch (day) {
        case 1:
            System.out.println("Monday");
        case 2:
            System.out.println("Tuesday");
        case 3:
            System.out.println("Wednesday");
        case 4:
            System.out.println("Thursday");
        case 5:
            System.out.println("Friday");
        case 6:
            System.out.println("Saturday");
        case 7:
            System.out.println("Sunday");
        default:
            System.out.println("Invalid key");
        }
Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Invalid key

we omitted break in all cases. It's execution starts from matching case till default case. because of this here we are seeing all cases output.

If we pass int day = 3 then matched case block is case 3, starts execution from there. Output will as following.

Wednesday
Thursday
Friday
Saturday
Sunday
Invalid key

If we add the break in all cases then will execute only matched case rather than all case blocks.

Java 7 Switch statement:

As of now, we have seen using primitive types in switch. But you may have got quetion why not using object in it.
In java 7, String are made legal to use in switch expression. String values are used to compare its values.

        String status = "AC";
        String statusString;
        switch (status) {
        case "AC":
            statusString = "Accepted";
            break;
        case "PR":
            statusString = "Processing";
            break;
        default:
            statusString = "Error occured";
        }
        System.out.println("Java 7 String switch example : " + statusString);

        
Output:

Java 7 String switch example : Accepted

Download Java 7 from Oracle.

Enum in Switch:

class EnumDemo {
    enum Gender {
        M("Male"), F("Female"), N("None");
        Gender(String s) {
            // enum constructor.
        }
    }
    public void enumSwitch() {
        Gender gender = Gender.M;
        switch (gender) {
        case M:
            System.out.println("You are male");
            break;
        case F:
            System.out.println("You are Female");
            break;
        default:
            System.out.println("You are not male, not female");
        }
    }
    public static void main(String[] args) {
        EnumDemo out = new EnumDemo();
        out.enumSwitch();
    }
}

Output:

You are male

Interview Questions:

What data types are allowed in switch?
char
byte
short
int
an enum (Added in Java 5)
String (Added in Java 7)

What is the use of default case?
If any one of cases value is not matched then default case will executed.

Should we use break statement in every case?
Yes but it is not mandatory.

Is break statement is optional?
These are optional. If we omit break then next case will be executed untill next break statemnt or default case.

If expression value is not matched constants in case?
If no case is matched then default block will be executed.

If we remove the break statement then what will happen?
If no break statement then continue with next cases.

If we remove the break statements in all cases then what will happen?
All cases will be executed from matched case.

Can we remove the default case?
Yes.

Shall we use String as expression?
Yes. It is legal from Java 7.

Is legal to use same constant in two cases?
Illegal. Give compile time error.

Can we pass Wrapper class instance to switch?
yes, We can pass Integer wrapper class. Allowed are Character, Byte, Short, Integer.

Can we pass a variable to case ? (Eg. int number=100, case number;)
No. Compile time error.

Can we use final on case constants?
Yes.

Can we use default case in middle of cases?
Yes.

Can we write code after break statement?
No. We will get compile time error saying "unreachable code".

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,13,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,78,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Switch Statement
Java Switch Statement
A detailed tutorial about the Switch statement in Java and its evolution over time. Java-W3schools blog. All cases of Switch Statement in Java 8 with interview Questions.
https://3.bp.blogspot.com/-0RkrsYieWxE/WaqAwtskcKI/AAAAAAAAAfk/LYJM4c6PITEfLnYEdFKx6vDCmk_h2cpMgCLcBGAs/s320/30%2BJava%2BSwitch%2BStatement.PNG
https://3.bp.blogspot.com/-0RkrsYieWxE/WaqAwtskcKI/AAAAAAAAAfk/LYJM4c6PITEfLnYEdFKx6vDCmk_h2cpMgCLcBGAs/s72-c/30%2BJava%2BSwitch%2BStatement.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2017/09/java-switch-statement.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2017/09/java-switch-statement.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content