Switch is mostly useful while we are making any menu-driven program and we can use switch even for many other purposes. Here I’m going to show you the use of switch which is very simple. Actually the switch work also can be done via if-else-if.
This example shows how to return the month name when we only give the month number.All the stuffs are being handled by the method getMethod() it will see if the month matches with the case from 1-12 if no any case is matched it would go to default: and returns ‘Invalid Month’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/** Here we are going to show how to display the Month name by giving only month number using 'switch' */ public class SwitchTest { //ATTRIBUTE private int month; //CONSTRUCTOR public SwitchTest(int m){ //setting value of month month = m; } //METHODS public String getMonth(){ //calling attribute by using static 'this' switch(this.month){ case 1: return "January"; break; case 2: return "February"; break; case 3: return "March"; break; case 4: return "April"; break; case 5: return "May"; break; case 6: return "June"; break; case 7: return "July"; break; case 8: return "August"; break; case 9: return "September"; break; case 10: return "October"; break; case 11: return "November"; break; case 12: return "December"; break; default: return "Invalid Month !!!"; } } //MAIN-METHOD public static void main(String args[]){ //Here we create a object by giving parameter '5' at constructor SwitchTest st = new SwitchTest(5); System.out.println("It's a " + getMonth()); } } |
In this code you can see the use of switch method .
This example demonstrates nothing. It is completely pointless. If you remove the ‘for’ loop and the switch statements and case labels and breaks the code will perform identically.
well dat’s need to be elaborate……….
man!
you have reminded now it’s my job to do this
example is good for beginners, I think U should add explanation part so that beginners can understand.
ya sure i’ll . Thanks..for comment