LogIn
I don't have account.

switch in java

DevSniper
166 Views

Switch is a control flow statement similar like if-else-if statement. Switch statement provides a structured way to execute multiple cases. It is a powerful control flow mechanism that enhances readability and can be particularly useful when dealing with multiple possible outcomes for a single variable/expression.

switch(expression)
{
   case x:
       //code 
       break;
   case y:
       // code
       break;
   ..............................
   ..............................
   default:
      // code
}
  • expression : It must be evaluate to a primitive type ( byte, short, int, long ) or String (from Java 7 onwards) or an enum.
  • switch expression can not be null.
  • case : switch statement can have n number of switch case.
  • Each switch case represents a possible value of the expression that is being evaluated.
  • The case value must be of switch expression type only. The case value must be constant or literal. It does not allow variables.
  • The case values must be unique. you will get compile-time error in case of duplicate value.
  • break : It terminates the switch statement and jump out from the switch block. Without break statement, execution falls through to the next case.
  • default : It is optional. It will execute if none of the case will match with expression value.
  • Switch statements is more efficient than multiple if-else statements, especially when there are many possible matches.
  • Switch statements can be nested within each other to handle complex decision trees.

Example : Week Days

public class RebootMemory
{
    public static String DayName(int day)
    {
        String dayName;
        switch (day) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
        }
        return dayName;
    }
    public static void main(String[] args) 
    {
        System.out.println("Day 1 is " + DayName(1));
        System.out.println("Day 7 is " + DayName(7));
        System.out.println("Day 5 is " + DayName(5));
        System.out.println("Day 8 is " + DayName(8));
        System.out.println("Day 3 is " + DayName(3));
    }
}
Day 1 is Monday
Day 7 is Sunday
Day 5 is Friday
Day 8 is Invalid day
Day 3 is Wednesday

Example : Month Name

public class RebootMemory 
{
    public static String MonthName(int month)
    {
        String monthName;
        switch (month) {
        case 1:
            monthName="January";
            break;
        case 2:
            monthName="February";
            break;
        case 3:
            monthName="March";
            break;
        case 4:
            monthName="April";
            break;
        case 5:
            monthName="May";
            break;
        case 6:
            monthName="June";
            break;
        case 7:
            monthName="July";
            break;
        case 8:
            monthName="August";
            break;
        case 9:
            monthName="September";
            break;
        case 10:
            monthName="October";
            break;
        case 11:
            monthName="November";
            break;
        case 12:
            monthName="December";
            break;
        default:
            monthName = "Invalid Month!";
        }
        return monthName;
    }
    public static void main(String[] args) 
    {
        System.out.println("Month 1 is "+ MonthName(1));
        System.out.println("Month 7 is " + MonthName(7));
        System.out.println("Month 5 is " + MonthName(5));
        System.out.println("Month 8 is " + MonthName(8));
        System.out.println("Month 13 is " + MonthName(13));
    }
}
Month 1 is January
Month 7 is July
Month 5 is May
Month 8 is August
Month 13 is Invalid Month!

Java Switch Statement is fall-through

Without break statement, execution falls through to the next case. that means it executes all statements after the first match if a break statement is not present.

public class RebootMemory 
{
    public static void main(String[] args) 
    {
        int number=3;
        switch(number) {
        case 1:
            System.out.println("Number is 1");
        case 2:
            System.out.println("Number is 2");
        case 3:
            System.out.println("Number is 3");
        case 4:
            System.out.println("Number is 4");
        case 5:
            System.out.println("Number is 5");
        default:
         System.out.println("Number is not matches 1 2 3 4 5");
        }
    }
}
Number is 3
Number is 4
Number is 5
Number is not matches 1 2 3 4 5

Java Switch Statement with String

Java allows developers to use strings in switch expression since Java SE 7. The case statement should be string literal.

public class RebootMemory 
{
    public static String getDayString(String day) 
    {
        String dayString="";
        switch (day) {
        case "Monday":
            dayString="Today is Monday.";
            break;
        case "Tuesday":
            dayString = "Today is Tuesday.";
            break;
        case "Wednesday":
            dayString = "Today is Wednesday.";
            break;
        case "Thursday":
            dayString = "Today is Thursday.";
            break;
        case "Friday":
            dayString = "Today is Friday.";
            break;
        case "Saturday":
        case "Sunday":
            dayString = "It's the weekend!";
            break;
        default:
            dayString = "Invalid day.";
        }
        return dayString;
    }
    public static void main(String[] args) {
        System.out.println("Monday :- " + getDayString("Monday"));
        System.out.println("Friday :- " + getDayString("Friday"));
        System.out.println("Saturday :- " + getDayString("Saturday"));
        System.out.println(" xyx :- " + getDayString("xyx"));
    }
}
Monday :- Today is Monday.
Friday :- Today is Friday.
Saturday :- It's the weekend!
xyx :- Invalid day.

Java Nested Switch Statement

When we use one switch statement inside other switch statement. It is known as nested switch statement. Java allow developer to handle more complex decision-making scenarios by nesting one switch statement inside another. developer can nest switch statement as much as he want.

public class RebootMemory 
{
    public static String getPositionString(int category,int level) 
    {
        String positionString="";
        switch (category) {
        case 1:
            switch (level) {
            case 1:
                positionString ="SDE";
                break;
            case 2:
                positionString = "SDE II";
                break;
            case 3:
                positionString = "TL";
                break;
            default:
                positionString ="Position not defined of this level in this category.";
            }
            break;
        case 2:
            switch (level) {
            case 1:
                positionString ="Product Manager";
                break;
            case 2:
                positionString = "Sr. Product Manager";
                break;
            case 3:
                positionString = "VP";
                break;
            default:
                positionString ="Position not defined of this level in this category.";
            }
            break;
        default:
            positionString ="Category not defined.";
        }
        return positionString;
    }

    public static void main(String[] args) 
    {
        System.out.println("Cat 1, level 2 => " +getPositionString(1,2));
        System.out.println("Cat 1, level 3 => " +getPositionString(1,3));
        System.out.println("Cat 1, level 5 => " +getPositionString(1,5));
        System.out.println("Cat 2, level 2 => " +getPositionString(2,2));
        System.out.println("Cat 3, level 1 => " +getPositionString(3,1));
        System.out.println("Cat 2, level 5 => " +getPositionString(2,5));
    }
}
Cat 1, level 2 => SDE II
Cat 1, level 3 => TL
Cat 1, level 5 => Position not defined of this level in this category.
Cat 2, level 2 => Sr. Product Manager
Cat 3, level 1 => Category not defined.
Cat 2, level 5 => Position not defined of this level in this category.