String In Switch-Java 7 New Concept

Introduction

In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.

Strings In Java

String are widely used in Java, they are a sequence of characters (sometimes called a character array). In Java, strings are objects.

Java provides the String class to create and manipulate strings.

How to Create a String

The general way to create a string is:

String welcome="welcome to Java world";

Let's see an example to display the simple string "Welcome".

public class StringEx
 
{
    public static void main(String args[])
      {
        char[] WelcomeArray = { 'W', 'e', 'l', 'c', 'o', 'm', 'e'};
        String WelcomeString = new String(WelcomeArray);
       
System.out.println( WelcomeString );
      }  
  }

Output

fig1.jpg

Switch case in Java

Switch statements reduce the workload, since without a switch we use if and else many times instead of the switch. Let's see a sample of if and else without a switch:

if (x == 0) doSomework0();
else if (x == 1) doSomework1();
else if (x == 2) doSomework2();
else if (x == 3) doSomework3();
else if (x == 4) doSomework4();
else doSomeworkElse();

Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write the above using a switch-case:

switch (x)
  {
    case 0:
    doSomework0();
    break;
    case 1:
   
doSomework1();
    break;
    case 2:
   
doSomework2();
    break;
    case 3:
   
doSomework3();
    break;
    case 4:
   
doSomework4();
    break;
    default:
   
doSomeworkElse();
 }

In this example x must be a variable. x is compared to each case value. In case 0 the x must be compared with x==0 if it is then subsequent code will execute, similarly x will work according to other cases. If no cases are matched then the default action is triggered.

Purpose of switch

The if statement only evaluates a boolean value (only two possible values True and False). The switch statement will execute on many expressions based on an integer (including char) or enum value.

Switch keywords

switch

The Switch statement is followed by an expression in paranthesis, that is followed by the cases, all enclosed in braces. The Switch statement works using cases dependent on the value of expressions.

Case

The case contain a colon and an integer constant.

default

If no case value matches the switch expression value then execution falls to the default clause. This is the equivalent of the last "else" for a series of if statements.

break

The break statement causes execution to exit to the statement after the end of the switch. If there is no break then execution flows thru into the next case. Flowing directly into the next case is nearly always an error.

Example

Let's see an example of how switch cases work!

import java.io.*;
public class SwitchEx
  {
    public static void main(String args[]) throws Exception
      {
        int choice;
        //
we make a month chart to test switch cases
        System.out.println("Enter 1 for January.");
        System.out.println("Enter 2 for Febrary");
        System.out.println("Enter 3 for March.");
        System.out.println("Enter 4 for April.");
        System.out.println("Enter 5 for May.");
        System.out.println("Enter 6 for June.");
        System.out.println("Enter 7 for July.");
        System.out.println("Enter 8 for August.");
        System.out.println("Enter 9 for September.");
        System.out.println("Enter 10 for October.");
        System.out.println("Enter 11 for November.");
        System.out.println("Enter 12 for December.");
        System.out.print("\n Whats your choice : ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try
          {
            choice=Integer.parseInt(in.readLine());
            switch(choice)
              {

                case 1: System.out.println("January");
                break;
                case 2: System.out.println("Febrary");
                break;
                case 3: System.out.println("March");
                break;
                case 4: System.out.println("April");
                break;
                case 5: System.out.println("May");
                break;
                case 6: System.out.println("June");
                break;
                case 7: System.out.println("July");
                break;
                case 8: System.out.println("August");
                break;
                case 9: System.out.println("September");
                break;
                case 10: System.out.println("October");
                break;
                case 11: System.out.println("November");
                break;
                case 12: System.out.println("December");
                break;
                default: System.out.println("Wrong entry!");
                break;
                }
           }
        catch(NumberFormatException ey)
          {
            System.out.println(ey.getMessage() + " enter only numeric value.");
            System.exit(0);
          }
      }
  }

Output

fig-2.jpg

String in switch: Java 7 new feature

Switch statements work either with primitive types (e.g byte, short, long, int, ect) or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.

The method of working on strings is crude. Java 7 improves the program by enhancing the Switch statement, that takes a String type as an argument.

Let's see a previous example using a String in a switch this time. In this example a string is invoked in the switch statement which can't be dne in prior versions of Java. So it might be helpul for reducing if-else statements.

public class StringSwitchEx
  {
    public static int getMonthNumber(String month)
      {
        int monthNumber = 0;
        if (month == null)
          {
            return monthNumber;
          }
        switch (month.toLowerCase())
          {
            case "january":
            monthNumber = 1;
            break;
            case "february":
            monthNumber = 2;
            break;
            case "march":
            monthNumber = 3;
            break;
            case "april":
            monthNumber = 4;
            break;
            case "may":
            monthNumber = 5;
            break;
            case "june":
            monthNumber = 6;
            break;
            case "july":
            monthNumber = 7;
            break;
            case "august":
            monthNumber = 8;
            break;
            case "september":
            monthNumber = 9;
            break;
            case "october":
            monthNumber = 10;
            break;
            case "november":
            monthNumber = 11;
            break;
            case "december":
            monthNumber = 12;
            break;
            default:
            monthNumber = 0;
            break;
          }
        return monthNumber;
      }
    public static void main(String[] args)
      {
        String month = "June";
        int returnedMonthNumber =StringSwitchEx.getMonthNumber(month);
        if (returnedMonthNumber == 0)
          {
            System.out.println("Invalid month");
          }
        else
          {
            System.out.print("The selected month no is : ");
            System.out.print(returnedMonthNumber);
          }
      }
  }

Output

fig-3.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all