Java enable string in switch

How to use String in Java switch-case statement

Since Java 7, programmers can use String in the switch-case statement. This simple feature had been waiting for a long time before becoming available in Java 1.7. Imagine we would have to use the following code to test a String variable against a list of values before Java 1.7:

String country = getCountry(); // get country from somewhere if (country.equals("USA")) < // invite American >else if (country.equals("UK")) < // invite British >else if (country.equals("Japan")) < // invite Japanese >else if (country.equals("China")) < // invite Chinese >else if (country.equals("France")) < // invite French >

Now with Java 1.7 we can replace the above if-else statements by this much simpler and cleaner switch-case statement:

String country = getCountry(); switch (country) < case "USA": // invite American break; case "UK": // invite British break; case "Japan": // invite Japanese break; case "China": // invite Chinese break; case "France": // invite French break; default: // unsupported country >

In this switch statement, the String variable country is compared with the String literals in the case clause by the equals() method of the String class.

It’s recommended to declare String constants to be used in the case clause like this:

// declare String constants in class level static final String USA = "USA"; static final String UK = "UK"; static final String JAPAN = "Japan"; static final String CHINA = "China"; static final String FRANCE = "France"; // get country from somewhere String country = getCountry(); // using Strings in switch-case statement switch (country) < case USA: // invite American break; case UK: // invite British break; case JAPAN: // invite Japanese break; case CHINA: // invite Chinese break; case FRANCE: // invite French break; default: // unsupported country >

So remember to use this new, handy language feature since Java 1.7.

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

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).
Читайте также:  Точный критерий фишера python

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

Источник

How to use String literals in switch case in Java? Example Tutorial

Switch Statements are not new for any Programmer, it is available in C, C++, Java and in all major programming language. The switch statement in Java allows you to a clear, concise, and efficient multiple-branch statement without lots and lots of messy if-else statements. But Java Switch and case statement have a limitation, you cannot use String in them. Since String is one of the most used classes in Java, and almost every program, starting from Hello World to a complex multi-tier Java application uses them, it makes a lot of sense to allow them in the Switch case. In Java 6 and before, the values for the cases could only be constants of integral type e.g. byte , char , short , int, and enum constants. If you consider Autoboxing then you can also use the corresponding wrapper class like Byte , Character , Short, and Integer .

From Java 1.7, language has been extended to allow String type in switch and case statement as well. This makes, Java programmer’s life a bit easier, as it no more has to map String to Integers, to use them inside switch constructs.

In this Java 1.7 tutorial, we will learn How to use Strings in switch in Java. Like many Project Coin enhancements, e.g. underscore in numeric literals, Automatic resource management, this is really a very simple change to make life in Java 7 easier.

This is not a JVM level change, instead it is implemented as syntactic sugar. In all other respects, the switch statement remains the same, and internally it uses equals and hashcode method to make it work.

Java Program to use String in Switch Statement

In our example of using Strings in Switch case, we are accepting a String command from console, and passing it to our execute method, which is like a remote control, execute the command given. If you look at the code, we have used String variables in switch as well as case. They don’t have to be upper case, but they are case sensitive, and that’s why keeping them in one case, preferably upper case is good for maintenance.

import java.util.Scanner; public class StringInSwitch public static void main(String args[]) < Scanner scnr = new Scanner(System.in); while(true) < System.out.println("Please enter command : "); String command = scnr.nextLine(); // command = command.toUpperCase(); execute(command); > > public static void execute(String command)  switch (command)  case "START": System.out.println("Starting . "); break; case "STOP": System.out.println("Stopping . "); break; case "REWIND": System.out.println("Rewinding . "); break; case "FORWARD": System.out.println("Forwarding . "); break; case "PAUSE": System.out.println("Pausing . "); break; case "SHUTDOWN": System.out.println("Shutting down .."); System.exit(0); break; default : System.out.println("Unknown Command"); > > > Output : Please enter command : Start Unknown Command Please enter command : START Starting . Please enter command : STop Unknonwn Command Please enter command : STOP Stopping . Please enter command : SHUTDOWN Shutting down ..

From output, you can see that Strings in Switch statements are case sensitive. When we enter Start , it says unknown command, but when we entered START , it executes that command. That’s why you should always convert user command into the either UPPER case or LOWER case, as required by your program, commented in our code for demonstration only.

Important things about Using String in Switch Statements

How to use String in Swith in Java 7

Here are a couple of important points about using String literal in switch statement feature in Java:

1) Strings in Switch are syntactic sugar, no change in JVM level.

2) Internally it uses the equals method to compare, which means, if you pass null it will throw java.lang.NullPointerException , so beware of that.

3) Strings in switch statements are case sensitive, prefer to use only one case and convert the input to the preferred case before passing them to switch statement.

4) The Java compiler generates generally more efficient byte code from switch statements that use String objects than from chained if-then-else statements. So prefer Strings with switch than nested if-else.

That’s all folks on using String in Switch statement in Java. This feature is available from Java 7 and you are free to use them but write robust code, which can sustain Strings case sensitivity issue. By the way switch statements have changed a lot in recent Java version with new Switch expressions which also allows you to add options in switch statements like shown below. You can learn more about switch expression on my earlier article

  • How to create String array from ArrayList in Java
  • How to count Vowels and Consonants in Java String
  • How to replace String in Java
  • How to use Substring in Java
  • How to use Regular Expression to Search in String
  • How to Split String in Java
  • How to convert String to Integer in Java
  • Best way to Convert Numbers to String in Java
  • How to search a character in Java String
  • How to check if a String contains at least one number in Java
  • ArrayList to String in Java
  • 3 Ways to Read InputStream as String in Java
  • How to remove whitespace form String in Java
  • How to reverse String in Java
  • Difference between StringBuilder and StringBuffer in Java
  • How to Check if String is Empty in Java
  • Difference between String and StringBuffer in Java
  • How to convert array to String in Java
  • Difference between String literal and String Object in Java
  • How to convert Enum to String in Java
  • Best way to compare String in Java

Источник

Java switch case String

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, 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"); >> > 
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) 
  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.

Источник

Оцените статью