24 Jan 2017

Simple Switch Example

Lets take an example of switch statement without break; :


class Week
{
      public static void main(String a[])
     {
           int day=2;
           switch(day)
           {
               case 1: System.out.println("Monday");
               case 2: System.out.println("Tuesday");
               case 3: System.out.println("Wednesday");
               case 4: System.out.println("Thursday");
               case 5: System.out.println("Friday");
               case 6: System.out.println("Saturday");
               case 7: System.out.println("Sunday");
           }
    }
}


If you execute this program the output is starting from case 2 Tuesday  and end with Sunday
 YOU know i had share you an example of ball and stairs that if you throw a ball to stairs then it falls back to you to you with each steps if their is no blocks like breaks . So tie break statements with each case condition. and then execute this program


this example is with break;

class Week
{
      public static void main(String a[])
     {
           int day=2;
           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;
               case 6: System.out.println("Saturday");break;
               case 7: System.out.println("Sunday");
           }
    }
}

execute it and then see the difference.


Follow me to  more learn basics with examples..😄😄😄😄😄😄




No comments:

Post a Comment