Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, February 6, 2019

Java Switch Statement



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".

No comments:

Post a Comment

Please do not add any spam links in the comments section.