Monday, January 13, 2020

switch statement in Java

The switch-statement in Java

The switch is a branching statement like if-else statements, but it is less used statement than if-else. The switch-statement is an alternative to if-else-ladder when there are several possible execution paths. A switch can work with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and some special classes that wrap certain primitive data types like Character, Byte, Short, and Integer (Wrapper classes).




Switch-case Syntax

  switch (key) 
   {
  case value-1:
     statement-1
   break;
  case value-2:
     statement-2
   break;
  case value-3:
     statement-3
   break;
  default:
    // default-statement;
   break;


Switch-case VS if-else ladder


The switch-statement can be more efficient than if-else as the time need to evaluate all these statements is higher, but in switch-case control can directly jump to the correct case. The break statements in the switch are not actually required by the syntax of the switch statement. The effect of a break is to let control jump past the end of the switch statement and skipping over all the remaining cases. If we leave out the break statement, the control will just keep executing statements after completing one case and will execute all the statements associated with the next case label. This is rarely required, but it is legal.

Switch-case statement example


/********swich-case example**********/
public class DemoSwitch {
    public static void main(String[] args) {
        int day=5;
        switch(day)
        {
        case 0:
            System.out.println("Sunday");
            break;
        case 1:
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thrusday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        default:
            System.out.println("Worng value");
            break;

        }
   
    }

}



Video Tutorial