Java Switch Statement Multiple Cases

Java switch statement multiple cases

Sadly, it's not possible in Java. You'll have to resort to using if-else statements.

Using two values for one switch case statement

You can use have both CASE statements as follows.

  case text1: 
case text4:{
//blah
break;
}

SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:

class SwitchDemo {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}

This is the output from the code:

Number of Days = 29

FALLTHROUGH:

Another point of interest is the break statement. Each break statement
terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements
are necessary because without them, statements in switch blocks fall
through
: All statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered.

EXAMPLE CODE:

public class SwitchFallThrough {

public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();

int month = 8;

switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}

if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}

This is the output from the code:

August
September
October
November
December

Using Strings in switch Statements

In Java SE 7 and later, you can use a String object in the switch
statement's expression. The following code example, ,
displays the number of the month based on the value of the String
named month:

public class StringSwitchDemo {

public static int getMonthNumber(String month) {

int monthNumber = 0;

if (month == null) {
return monthNumber;
}

switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}

return monthNumber;
}

public static void main(String[] args) {

String month = "August";

int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);

if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}

The output from this code is 8.

FROM Java Docs

Java - switch case, Multiple cases call the same function

You have to use case keyword for each String like this :

switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
handleFruit();
break;
}

Edit 02/05/2019

Java 12

From Java 12 there are a new syntax of switch case proposed, so to solve this issue, here is the way:

switch (str) {
case "apple", "orange", "pieapple" -> handleFruit();
}

Now, you can just make the choices separated by comma, the an arrow -> then the action you want to do.

Another syntax also is :

consider that each case return a value, and you want to set values in a variable, lets suppose that handleFruit() return a String the old syntax should be :

String result;  //  <-------------------------- declare 
switch (str) {
//which mean if String equals to
case "apple": // apple
case "orange": // or orange
case "pieapple": // or pieapple
result = handleFruit(); // <----- then assign
break;
}

now with Java 12, you can make it like this :

String result = switch (str) { //  <----------- declare and assign in one shot
case "apple", "orange", "pieapple" -> handleFruit();
}

Nice syntax

Using switch statement with a range of value in each case?

after reading all the comments I didn't see anybody mention enhanced switch in which
you can have multiple values in one case like this ->

switch(value){
case 1,2,3,4:
//dosth
break;
case 7,9,10,23:
//dosth
break;
}

and since in your case, there is only one expression in every case, you can do the following without the need to break every case->

switch (value) {
case 1, 2, 3, 4 -> System.out.println("one of 1,2,3,4 matched");
case 7, 9, 10, 23 -> System.out.println("one of 7,9,10,23 matched");
}

this is one of the many added benefits with enhanced switches in java.

Switch statement for multiple cases in JavaScript

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;

default:
alert('Default case');
}

Java switch case statement - multiple entries for a case

Use this

switch(in){
case 0:
case 1:
//statement1 ; // now statement1 valid for both case 0 and 1
break;
case 2:
//statement2
break;

}

IdeOne example.

Can you connect two cases of a switch statement using a comma

Your original code segment uses fall-through to give the same response for both cases; some people find this difficult to read and follow. Java 12 gave us two related features that people find help clean up their switch statements, one of which you've discovered here:

  1. cases can be comma separated rather than relying on fall-through
  2. the arrow label can be used instead of the colon and break; commands.

Therefore, if you find yourself not liking fall-through, and not wanting to worry about whether you remembered your break commands, you can write the switch as follows:

switch (element) {
case hi, hello -> // do something here
case goodbye, bye -> // do something else here
}

Notice that in this case, we don't have any break statements, but there is no fall-through between the hi case and the bye case; they are separate due to the arrow label.

Can there be multiple value assignments for the enhanced switch statement?

There's no tuple unpacking in Java. A quick alternative that still uses a switch expression could use a custom class (using Pair in the following example):

Pair<Boolean, String> val = switch (num) {
case 0 -> Pair.of(true, "zero!");
case 1 -> Pair.of(true, "one!");
default -> Pair.of(false, "unknown :/");
};

boolean val1 = val.getLeft();
String val2 = val.getRight();


Related Topics



Leave a reply



Submit