Java 7 – Switch Expressions with Strings

Switch statement existed before Java 7 as well, but it supported only int and enum types. After Java 7 release, switch statement started supporting String class also.

1. Switch Expression with Strings

Java program to use String class in switch statements.

public class StringSupportedInSwitch
{
	public static void main(String[] args)
	{
		System.out.println(getExpendedMessage("one"));
		System.out.println(getExpendedMessage("three"));
		System.out.println(getExpendedMessage("five"));
	}

	static String getExpendedMessage(final String token)
    {
        String value = null;

        switch (token)
        {
            case ("one"):
                value = "Token one identified";
                break;

            case ("two"):
                value = "Token two identified";
                break;

            case ("three"):
                value = "Token three identified";
                break;

            case ("four"):
                value = "Token four identified";
                break;

            default:
                value = "No token was identified";
       }

        return value;
    }
}

Program Output.

Token one identified
Token three identified
No token was identified

2. Switch Expression to Handle Multiple Cases

Sometimes, we want to perform a certain action on multiple cases in the switch statement. In this case, we can write each value in a separate case and only after all cases are written, write down application logic.

For example, in the given program, all odd tokens will be handled by the first switch case, and even tokens will be handled by the second switch case.

public class StringSupportedInSwitch {

	public static void main(String[] args)
	{
		System.out.println(getExpendedMessage("one"));
		System.out.println(getExpendedMessage("two"));
	}

	static String getExpendedMessage(final String token)
	{
		String value = null;

		switch (token)
		{
			case ("one"):
			case ("three"):
				value = "Odd token identified";
				break;

			case ("two"):
			case ("four"):
				value = "Even token identified";
				break;

			default:
				value = "No token was identified";
		}

		return value;
	}
}

Program Output.

Odd token identified
Even token identified

In this example, we learned to use Java switch statements with strings. This feature was introduced in Java 7.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

2 thoughts on “Java 7 – Switch Expressions with Strings”

  1. 2. Java switch statement case handle multiple values

    Code snippet was incorrect for case 2, seems first code itself copied over there too. Please correct it.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.