Jul 17, 2014

Switch Statement in Java

We Can Use Switch Statement for Do Many Different Things Depending On One Variable. For Example You May Have Variable Called Month To Store The Month From 1 to 12. Depending On The Month You can Do Multiple Things.

Following Example Demonstrate How To Use Switch Statement.

class EasyCodeStuff {
   public static void main(String args[]){
      
      int MyMonth = 2;

      switch(MyMonth){

      case 1:
         System.out.print("January");
         break;
      case 2:
         System.out.print("February");
         break;
      case 3:
         System.out.print("March");
         break;
               case 4:
         System.out.print("April");
         break;
      case 5:
         System.out.print("May");
         break;
      case 6:
         System.out.print("June");
         break;
      case 7:
         System.out.print("July");
         break;
      case 8:
         System.out.print("August");
         break;
      case 9:
         System.out.print("September");
         break;
      case 10:
         System.out.print("October");
         break;
      case 11:
         System.out.print("November");
         break;
      case 12:
         System.out.print("December");
         break;
      default:
         System.out.print("Invalid Month");
         break;
      }
   }
}

Above Example Will Give The Out Put As "February".Because The Value Of The "MyMonth" Variable Is 2.

"case 1" Mean , Value Of "MyMonth" Variable Is 1. After The Colon(:) You Can Write Your Codes, What You Want To Do After "MyMonth" Variable Have Value 1.But Make Sure You Have Put A "break;" Statement In Last Line.

In The Following Example You Can See Their Statement Called "default;" After The Last Case Statement. This Section Execute If Non Of The Case Are Not True. 


No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...