Yes, you can use spaces in switch statement strings. As the other comment said, you're probably using the next() function instead of nextLine() which gets the next set of characters until it sees a space, while nextLine() gets the entire input. Answer from mblan180131 on reddit.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › strings-switch.html
Strings in switch Statements
1 month ago - The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more ...
🌐
Reddit
reddit.com › r/javahelp › can you have a string switch case with a space?
r/javahelp on Reddit: Can you have a string switch case with a space?
October 2, 2022 -

Hey guys. I'm pretty sure I'm a simple fix away from completing one of my assignments but I'm having a little bit of a problem with my switch case. I just want to see if it's possible to have a blank space in a string switch case because my code is not doing what I want it to do. This is my code for that portion.

switch(ans){
case "Italy":
System.out.println("Thank you!");
it++;
break;
case "Costa Rica":
System.out.println("Thank you!");
cr++;
break;
case "Pax Bisonica":
System.out.println("Thank you!");
pb++;
break;
case "Ghana":
System.out.println("Thank you!");
gh++;
break;

If anyone can help me with the Costa Rica and Pax Bisonica cases that would be great!

Discussions

java - Why can't I use switch statement on a String? - Stack Overflow
Is this functionality going to be put into a later Java version? Can someone explain why I can't do this, as in, the technical way Java's switch statement works? More on stackoverflow.com
🌐 stackoverflow.com
Use string in switch case in java - Stack Overflow
PS.. changing to a switch statement will do nothing for your complexity.. It is still the same number of paths. Just implemented differently. ... since efficiency came into question, afk else if would be better instead from the second "if" onwards ... Java (before version 7) does not support String ... More on stackoverflow.com
🌐 stackoverflow.com
design - What is the benefit of switching on Strings in Java 7? - Software Engineering Stack Exchange
When I was starting to programme in Java, the fact that switch statements didn't take strings frustrated me. Then on using Enums, I realised the benefits that you get with them rather than passing ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 16, 2013
How switch case with string(come in java 1.7) work internally? - Stack Overflow
I have one query related to switch case with string, How jvm work internally in case of switch case with string(feature come in java 1.7)? ... The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › string-in-switch-case-in-java
String in Switch Case in Java - GeeksforGeeks
July 23, 2025 - Hence the concept of string in switch statement arises into play in JDK 7 as we can use a string literal or constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the ...
🌐
Baeldung
baeldung.com › home › java › core java › java switch statement
Java Switch Statement | Baeldung
November 5, 2025 - Of course, we can’t also pass null as a value to the case label of a switch statement. If we do, the code will not compile. If we try to replace the DOG case value with the variable dog, the code won’t compile until we mark the dog variable as final: final String dog="DOG"; String cat="CAT"; switch (animal) { case dog: //compiles result = "domestic animal"; case cat: //does not compile result = "feline" }
Top answer
1 of 14
1026

Switch statements with String cases have been implemented in Java SE 7, at least 16 years after they were first requested. A clear reason for the delay was not provided, but it likely had to do with performance.

Implementation in JDK 7

The feature has now been implemented in javac with a "de-sugaring" process; a clean, high-level syntax using String constants in case declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.

A switch with String cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an if statement that tests string equality; if there are collisions on the hash, the test is a cascading if-else-if. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.

Switches in the JVM

For more technical depth on switch, you can refer to the JVM Specification, where the compilation of switch statements is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.

If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the tableswitch instruction.

If the constants are sparse, a binary search for the correct case is performed—the lookupswitch instruction.

In de-sugaring a switch on String objects, both instructions are likely to be used. The lookupswitch is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a tableswitch.

Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the O(1) performance of tableswitch generally appears better than the O(log(n)) performance of lookupswitch, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote a great article that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.

Before JDK 7

Prior to JDK 7, enum could approximate a String-based switch. This uses the static valueOf method generated by the compiler on every enum type. For example:

Pill p = Pill.valueOf(str);
switch(p) {
  case RED:  pop();  break;
  case BLUE: push(); break;
}
2 of 14
128

If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
   case MILK: lap(); break;
   case WATER: sip(); break;
   case BEER: quaff(); break;
   case OTHER: 
   default: dance(); break;
}
🌐
JA-VA Code
java-performance.info › home › string in case of a switch in java
Switch Case Java String: A Guide
September 28, 2023 - When it comes to managing program flow in Java, the switch statement is a versatile tool. Traditionally, it’s used for handling integer cases. However, starting with Java 7, you can use switch with strings, providing a more elegant and efficient way to manage multiple string comparisons.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-switch-case-string
Java switch case String | DigitalOcean
August 4, 2022 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › switch-statement-in-java
Switch Statements in Java - GeeksforGeeks
Java switch expression must be of byte, short, int, long(with its Wrapper type), enums and string. Beginning with JDK7, it also works with enumerated types (Enums in java), the String class, and Wrapper classes. This flowchart shows the control flow and working of switch statements:
Published   4 days ago
🌐
Dummies
dummies.com › article › technology › programming-web-design › java › use-strings-java-switch-statement-239328
How to Use Strings in a Java Switch Statement | dummies
June 29, 2025 - Starting with Java 7, you can set it up so that the case to be executed in a switch statement depends on the value of a particular string.
🌐
Medium
medium.com › @javatechie › the-evolution-of-switch-statement-from-java-7-to-java-17-4b5eee8d29b7
The Evolution Of Switch Statement From Java 7 to Java 17 | by Java Techie | Medium
December 24, 2021 - And through the arrow operator the string “It is an integer ” is returned . Let’s take this use case. Inside the case label where I have checked for a “Employee” instance , I want to do an additional check. Thinking traditionally , you could be doing this after the case statement. ... But Java 17 has introduced “Guarded Patterns” . You can do this check in the case label itself like below · return switch (obj) { case Integer i -> "It is an integer"; case String s -> "It is a string"; case Employee employee && employee.getDept().equals("IT") -> "IT Employee"; default -> "It is none of the known data types"; };
Top answer
1 of 8
12

As far as I can tell, the question is why wrapping String constants into enum hasn't been considered sufficient to cover the needs of language users. This has been addressed in the official feature proposal announced at JDK 7 (project Coin) mailing list.

Per my reading of the proposal, alternative of using enums has been dismissed on the ground that it introduces types bloat. For your convenience, relevant part of the proposal is quoted below, with the statement addressing enums quoted in bold:

MAJOR ADVANTAGE: What makes the proposal a favorable change?

More regular coding patterns can be used for operations selected on the basis of a set of constant string values; the meaning of the new construct should be obvious to Java developers.

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

Potentially better performance for string-based dispatch code.

MAJOR DISADVANTAGE: There is always a cost.

Some increased implementation and testing complexity for the compiler.

ALTERNATIVES: Can the benefits and advantages be had some way without a language change?

No; chained if-then-else tests for string equality are potentially expensive and introducing an enum for its switchable constants, one per string value of interest, would add another type to a program without good cause...

2 of 8
8

Apart from making the code more readable, there are potential performance gains relative to if/else if comparisons. Whether the change is worthwhile depends on how many comparisons you would be making. A string switch will be emitted as two separate switch instructions. The first operates on hash codes, so it tends to be a lookupswitch, ultimately yielding O(log n) complexity. The second is always a perfect O(1) tableswitch, so the combined complexity is still O(log n). A single, linear chain of if/else if statements would give slightly worse O(n) complexity.

If you're comparing more than, say, three strings, then a switch is probably more readable and compact. It will likely perform better, though you are unlikely to notice a difference unless you are doing a large number of comparisons on a hot code path.

🌐
Coderanch
coderanch.com › t › 503782 › java › string-switch
can we use string in switch (Beginning Java forum at Coderanch)
July 22, 2010 - Praveen Kumar wrote:We can not use Strings inside the Switch statement. But we can use Compiletime Constants like final String TEMP in LABEL of the Switch statement. Ah, no. In current Java releases (JDK 6), we cannot use Strings inside a switch statement, period.
🌐
Jenkov
jenkov.com › tutorials › java › switch.html
Java switch Statements
Before Java 7 this variable has to be numeric and must be either a byte, short, char or int. From Java 7 the variable can also be a String It is also possible switch on a Java enum variable.
🌐
Programiz
programiz.com › java-programming › examples › implement-switch-on-strings
Java Program to Implement switch statement on strings
// Java Program to implement String on switch statements in Java class Main { public static void main(String[] args) { // create a string String language = "Java"; switch(language) { case "Java": System.out.println(language + " is famous for enterprise applications."); break; case "JavaScript": System.out.println(language + " is famous for frontend and backend."); break; case "Python": System.out.println(language + " is famous for ML and AI."); break; default: System.out.println(language + " not found on record."); break; } } }
🌐
DataCamp
datacamp.com › doc › java › java-switch-statement
Java Switch Statement
Expression Types: The switch expression can be of type byte, short, int, char, String, or an enum. Avoid Complex Logic: Use switch for simple scenarios with discrete values. For complex conditions, consider using if-else statements. Java 12+ Enhancements: In Java 12 and later, switch expressions ...
🌐
Vultr Docs
docs.vultr.com › java › examples › implement-switch-statement-on-strings
Java Program to Implement switch statement on strings | Vultr Docs
December 23, 2024 - The switch statement in Java provides ... used with primitive types like int and char, Java SE 7 introduced the ability to use the switch statement with strings as well....
🌐
TutorialsPoint
tutorialspoint.com › can-we-use-switch-statement-with-strings-in-java
Can we use Switch statement with Strings in java?
July 30, 2019 - 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; } } }