Monday, 10 November 2014

The switch statement in Java

The "switch" statement works with any values that can be implicitly casted to an "int": "char", "byte", "short", "int" and also "enum". Therefore "switch" does not work with: "long", "float" and "double".

Since Java 7, it is also possible to use a String in the switch statement.

Eg.
int x = 2;

switch(x) {

   case 1: {
      System.out.println("x = 1");
      break;
   }

   case 2: {
      System.out.println("x = 2");
      break;
   }

   default: {
      System.out.println("default, x = "+x);
   }
}


Displays "x = 2"

Note that the order of the statement "default" does not matter. The example below will work in the same way than the previous example:
int x = 2;

switch(x) {

   case 1: {
      System.out.println("x = 1");
      break;
   }

   default: {
      System.out.println("default, x = "+x);
      break;
   }

   case 2: {
      System.out.println("x = 2");
      break;
   }
}

Displays "x = 2"

Important: the value in the statement "case" should be a compile time constant. For example a wrapper can not be used even if it is declared as a constant:
// Correct, but the compiler does not see an Object 
// as a constant; you can not use it in the statement 'case'.
public final static Integer age = 15;

// Can be used in 'case'
public final static int age2 = 15;

// Can be used in 'case'
public final int age3 = 15;

// An full example below:
final int a = 1;
int b = 2;
int x = 2;

switch(x) {

   // OK
   case a: { 
      System.out.println("x = 1");
      break;
   }

   // Compilation error as "b" is not a compile time constant
   case b: {
      System.out.println("x = 2");
      break;
   }

   default: {
      System.out.println("default, x = "+x);
   }
}

Even if you use a compile time constant, be careful that its type match with the type of the variable "x" in "switch(x)":
byte x = 2;

switch(x) {

   // Ok as 23 is implicitly casted into byte
   case 23: {
      System.out.println("x = 1");
      break;
   }

   // Compilation error as 128 is above a byte's range (max 127);
   // therefore it should be explicitly casted into byte: (byte)128
   case 128: {
      System.out.println("x = 2");
      break;
   }


   default: {
     System.out.println("default, x = "+x);

   }
}