switch statement in java
switch statements is similar to if-else-if ladder in java . It execute one statement from multiple conditions. A switch statement have an optional default case which can be appear at the end of switch . Default case will execute when none of conditions are matched . Default case has no break statement . Each case must have break otherwise the flow of control will fall until a break is reached . switch works with byte,int,short,char primitive data types . It also works with Enum types , String class etc.
Syntax :
Find us :
Facebook : @apnaandroid
Google+ : Apna Java
YouTube : Android & Java Tutorial
Syntax :
switch(expression) {
case value :
// statements
break;
case value :
// statements
break;
default :
// statements
}
Example :
public class SwitchDemoExample {
public static void main(String[] args) {
int month = 5;
String strMonth;
switch (month) {
case 1: strMonth = "Jan";
break;
case 2: strMonth = "Feb;
break;
case 3: strMonth = "Mar";
break;
case 4: strMonth = "Apr";
break;
case 5: strMonth = "May";
break;
case 6: strMonth = "June";
break;
case 7: strMonth = "July";
break;
case 8: strMonth = "Aug";
break;
case 9: strMonth = "Sept";
break;
case 10: strMonth = "Oct";
break;
case 11: strMonth = "Nov";
break;
case 12: strMonth = "Dec";
break;
default: strMonth = "Invalid month";
break;
}
System.out.println(strMonth);
}
}
Output : May
Find us :
Facebook : @apnaandroid
Google+ : Apna Java
YouTube : Android & Java Tutorial
Comments
Post a Comment