Java Switch statements : Executing same code for two values without redundant code

This is something I learnt recently. Assume that you want to execute the same code when the switch variable value is one of multiple values. This can be dine without repeating the same code in multiple case statements.

For example consider below code. There two case statements that check value for 3 or 4, executes same code block.  We can do this without duplicating the code.


switch (number) {

 case (1):
  System.out.println("Number is 1");
  break;
 
 case (2):
  System.out.println("Number is 2");
  break;
 
 case (3):
  System.out.println("Number is 3 or 4");
  break;
 
 case (4):
  System.out.println("Number is 3 or 4");
  break;
 
 default:
  System.out.println("Number is not 1, 2, 3 or 4");
  break;

  }

See below.

switch (number) {

 case (1):
  System.out.println("Number is 1");
  break;
 
 case (2):
  System.out.println("Number is 2");
  break;
 
 case (3):case (4):
  System.out.println("Number is 3 or 4");
  break;
 
 default:
  System.out.println("Number is not 1, 2, 3 or 4");
  break;

  }



Comments

Popular posts from this blog

How to add Maven dependency from a relative path referencing a local jar

Manually install a maven dependency

PHP-SOAP web service with out a WSDL