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
🌐
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!

🌐
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.
Discussions

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
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
The Switch vs. If-then-else statements - Java - Code with Mosh Forum
I think this detail might be of general interest: The use-case for using the switch statement instead of the if-then-else statement, is a question of readability (preference) - but only in cases where you’re testing expressions based on single values. Cited: Deciding whether to use if-then-else ... More on forum.codewithmosh.com
🌐 forum.codewithmosh.com
0
June 10, 2022
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › strings-switch.html
Strings in switch Statements
3 weeks 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 ...
🌐
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"; };
🌐
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 ...
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.

Find elsewhere
🌐
SoftwareMill
softwaremill.com › java-21-switch-the-power-on
Java 21: switch the power on | SoftwareMill
October 2, 2023 - This is also the case in Java 21, ... lets you avoid the NPE. ... String test = null; switch (test) { case String s -> System.out.println("String"); case null -> System.out.println("null"); }...
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;
}
🌐
W3Schools
w3schools.com › java › java_switch.asp
Java Switch
Strings Concatenation Numbers and Strings Special Characters Code Challenge Java Math Java Booleans · Booleans Real-Life Example Code Challenge Java If...Else · if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch
🌐
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" }
🌐
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.
🌐
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.
🌐
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.
🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 01 › evolution-of-the-switch-construct-in-java-why-should-you-care
Evolution of the Switch Construct in Java—Why Should you Care? | The IntelliJ IDEA Blog
January 30, 2024 - In Java 23, you might be able to use primitive types in patterns too. Unlike a switch statement, Switch expressions can return a value, without needing a break statement at the end of each case label. Pattern matching for switch significantly reduces the count of lines of code you need for an equivalent if-else construct. It enables you to switch on a lot of data types rather than just a handful of primitives, enums and String (as was the case with the older switch constructs).
🌐
Code with Mosh
forum.codewithmosh.com › java
The Switch vs. If-then-else statements - Java - Code with Mosh Forum
June 10, 2022 - I think this detail might be of general interest: The use-case for using the switch statement instead of the if-then-else statement, is a question of readability (preference) - but only in cases where you’re testing expressions based on single values. Cited: Deciding whether to use if-then-else ...
🌐
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 ...
🌐
nipafx
nipafx.dev › java-switch
How To Use switch In Modern Java // nipafx
April 19, 2022 - var string = switch (number) { case 1, 2 -> "few"; default -> "many"; }; Super handy to replace trivial fall-through. The details of pattern matching in switch are still in flux (there'll be a third preview in Java 19), so this section is somewhat ...