- Can we use Switch statement with Strings in java?
- Syntax
- Strings in switch
- Example
- Output
- Java switch case String
- Java Switch Case
- Java switch case String Example
- Java String Switch Case Example
- Java String Switch Case Example
- Java String Switch Case vs if-else
- Important Points for String in Switch Case
- References:
Can we use Switch statement with Strings in java?
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax
Strings in switch
Yes, we can use a switch statement with Strings in Java. While doing so you need to keep the following points in mind.
- It is recommended to use String values in a switch statement if the data you are dealing with is also Strings.
- The expression in the switch cases must not be null else, a NullPointerException is thrown (Run-time).
- Comparison of Strings in switch statement is case sensitive. i.e. the String you have passed and the String of the case should be equal and, should be in same case (upper or, lower).
Example
Following example demonstrates the usage of String in switch statement.
import java.util.Scanner; public class SwitchExample < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Available models: Activa125(act125), Activa5G(act5g)," + " Accesses125(acc125), Vespa(ves), TvsJupiter(jup)"); System.out.println("Select one model: "); String model = sc.next(); switch (model) < case "act125": System.out.println("The price of activa125 is 80000"); break; case "act5g": System.out.println("The price of activa5G is 75000"); break; case "acc125": System.out.println("The price of access125 is 70000"); break; case "ves125": System.out.println("The price of vespa is 90000"); break; case "jup": System.out.println("The price of tvsjupiter is 73000"); break; default: System.out.println("Model not found"); break; >> >
Output
Available models: Activa125(act125), Activa5G(act5g), Accesses125(acc125), Vespa(ves), TvsJupiter(jup) Select one model: act125 The price of activa125 is 80000
Java switch case String
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.
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 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"); >> >
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)
- Java switch case String make code more readable by removing the multiple if-else-if chained conditions.
- Java switch case String is case sensitive, the output of example confirms it.
- 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.
- 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.
- 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.
Java String Switch Case Example
Java 7 started support for using String in switch case. In earlier versions, if you have to write conditional logic based on a string, you had to use if-else blocks.
Java String Switch Case Example
Let’s look at some examples of using string in switch case statements.
package net.javastring.strings; import java.util.Scanner; public class JavaStringSwitchCase < public static void main(String[] args) < System.out.print("Please enter any programming language:\n"); Scanner scanner = new Scanner(System.in); String input = scanner.next(); scanner.close(); switch (input) < case "java": System.out.println("Java Current Version is 12."); break; case "python": System.out.println("Python Current Version is 3.7"); break; case "rust": System.out.println("Rust Current Version is 1.34.1"); break; default: System.out.println("We don't have information about this programming language"); >> >
Java String Switch Case vs if-else
Let’s have a look at the alternate implementation of above code using if-else block.
if ("java".equals(input)) System.out.println("Java Current Version is 12."); else if ("python".equals(input)) System.out.println("Python Current Version is 3.7"); else if ("rust".equals(input)) System.out.println("Rust Current Version is 1.34.1"); else System.out.println("We don't have information about this programming language");
Important Points for String in Switch Case
- Java switch case with string is more readable than the multiple if-else if-else blocks.
- The switch case matching is case sensitive, so “java” will not match for input string “Java”.
- If the input string is null, switch-case will throw NullPointerException. So have a null check in place before writing the switch-case code.
- The bytecode generated by switch-case is more efficient than the if-else blocks. You can check this in the reference article below.
- You can convert the input string and all the case values to either uppercase or lowercase for case insensitive match.