Tutorial

Java switch case String

Published on August 4, 2022
author

Pankaj

Java switch case String

Today we will look into Java Switch Case String Example. Being a java programmer, I know the importance of String and how many times it’s used for conditional flow. Whether you have a simple method that behaves differently for different input String or a Servlet controller class to check the incoming action and process it accordingly, we use String and compare it to determine the flow.

Java Switch Case

java switch case, java switch string Java switch case is a neat way to code for conditional flow, just like if-else conditions. Before Java 7, the only means to achieve string based conditional flow was using if-else conditions. But Java 7 has improved the switch case to support String also.

Java switch case String Example

Here I am providing a java program that shows the use of String in java switch case statements. For comparison, I am also providing another method which does the same conditional flow using if-else conditions. SwitchStringExample.java

package com.journaldev.util;

public class SwitchStringExample {

	public static void main(String[] args) {
		printColorUsingSwitch("red");
		printColorUsingIf("red");
		// switch case string is case sensitive
		printColorUsingSwitch("RED");
		printColorUsingSwitch(null);
	}

	private static void printColorUsingIf(String color) {
		if (color.equals("blue")) {
			System.out.println("BLUE");
		} else if (color.equals("red")) {
			System.out.println("RED");
		} else {
			System.out.println("INVALID COLOR CODE");
		}
	}

	private static void printColorUsingSwitch(String color) {
		switch (color) {
		case "blue":
			System.out.println("BLUE");
			break;
		case "red":
			System.out.println("RED");
			break;
		default:
			System.out.println("INVALID COLOR CODE");
		}
	}

}

Here is the output of the above program.

RED
RED
INVALID COLOR CODE
Exception in thread "main"
java.lang.NullPointerException
	at com.journaldev.util.SwitchStringExample.printColorUsingSwitch(SwitchStringExample.java:24)
	at com.journaldev.util.SwitchStringExample.main(SwitchStringExample.java:10)

Keys points to know for java switch case String are:

  1. Java switch case String make code more readable by removing the multiple if-else-if chained conditions.
  2. Java switch case String is case sensitive, the output of example confirms it.
  3. Java Switch case uses String.equals() method to compare the passed value with case values, so make sure to add a NULL check to avoid NullPointerException.
  4. According to Java 7 documentation for Strings in Switch, java compiler generates more efficient byte code for String in Switch statement than chained if-else-if statements.
  5. Make sure to use java switch case String only when you know that it will be used with Java 7 else it will throw Exception.

Thats all for Java switch case String example. Tip: We can use java ternary operator rather than switch to write smaller code.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 10, 2021

How can we apply null check in switch case

- Srishti

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 24, 2018

    why switch was not supported in earlier version of java 7 ?

    - Vijay

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 19, 2017

      Hi Pankaj, The case sensitivity will not work, when the switch case label is changed as below (from lowercase red to RED, on supplying printColorUsingSwitch(“red”) private static void printColorUsingSwitch(String color) { switch (color) { case “blue”: System.out.println(“BLUE”); break; case “RED”: System.out.println(“RED”); break; default: System.out.println(“INVALID COLOR CODE”); } }

      - Suresh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 29, 2017

        can anyone explain following? “java compiler generates more efficient byte code for String in Switch statement than chained if-else-if statements.”

        - alok

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 2, 2014

          very nice

          - aparna

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Become a contributor for community

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            DigitalOcean Documentation

            Full documentation for every DigitalOcean product.

            Resources for startups and SMBs

            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

            Get our newsletter

            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

            New accounts only. By submitting your email you agree to our Privacy Policy

            The developer cloud

            Scale up as you grow — whether you're running one virtual machine or ten thousand.

            Get started for free

            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

            *This promotional offer applies to new accounts only.