Core JAVA

String In Switch-Java 7 New Concept

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.

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:
Welcome

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 parenthesis, 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:

String in switch: Java 7 new feature

Switch statements work either with primitive types (e.g byte, short, long, int, etc) 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 end in prior versions of Java. So it might be helpful 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:

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago