Sunday, 28 August 2016

Java switch

3. Conditional Statement switch
  • To choose one option from more options then we should go for this switch statement.
  • To choose one option from more options we can go for if_else_if statement but using switch is the best solution.
syntax

switch(variable)
{
       case value 1: statement1;
                          break;
       case value2:  statement2;
                          break;
       default: default statement;
}
  --------------------------------------------------------------------------------
Program         :       Basic program switch statement to find weekday
Program name  :      SwitchDemo1.java
Output            : 
                             Friday

class SwitchDemo1
{
     public static void main(String s[])
    {
        int day = 5;
        
        switch(day)
        {
            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("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            default:
                System.out.println("Weekend");
                break;
        }
    }
}

Compile     :            javac SwitchDemo1.java
Run           :            java SwitchDemo1
Output       : 
                             Friday             
  --------------------------------------------------------------------------------

Thanks for your time.
- Nireekshan