You can't switch on conditions like x. contains() . Java 7 supports switch on Strings but not like you want it. Use if etc.
Yes, we can use a switch statement with Strings in Java.
String is the only non-integer type which can be used in switch statement.
A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).
How can I convert the following code to switch statement?
String x = "user input";
if (x.contains("A")) {
//condition A;
} else if (x.contains("B")) {
//condition B;
} else if(x.contains("C")) {
//condition C;
} else {
//condition D;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With