java switch case multiple values code example

Example 1: Java switch case with multiple values

// Java switch case with multiple values
public class SwitchCaseMultipleValues
{
   public static void main(String[] args)
   {
      int number = 1;
      switch(number)
      {
         case 1: case 2:
             System.out.println("number 1");
             System.out.println("number 2");
             break;
         case 3:
             System.out.println("number 3");
             break;
         default:
             System.out.println("number is not 1, 2 or 3");
      }
   }
}

Example 2: java switch multiple values

switch (num) {
            case 5:
            case 2:
            case 3:
                System.out.println("5,2,3");
                break;
            case 4:
            case 6:
                System.out.println("4,6");
                break;
            case 1:
                System.out.println("1");
                break;
            default:
                System.out.println("Inavlid number");
                break;
        }

Example 3: multiple case switch java

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

Example 4: Java switch with multiple cases

// Java switch with multiple cases
public class SwitchMultipleCase
{
   public static void main(String[] args)
   {
      System.out.println(multipleCase("one"));
      System.out.println(multipleCase("two"));
   }
   static String multipleCase(final String number)
   {
      String str = null;
      switch(number)
      {
         case("one"):
         case("three"):
         case("five"):
             str = "odd numbers";
         break;

         case("two"):
         case("four"):
         case("six"):
             str = "even numbers";
         break;
         default:
             str = "please enter valid input";
      }
      return str;
   }
}

Tags:

Java Example