I was just wondering if default case MUST be included in switch statements in Java. I understand it is good practice to include default cases. The reason why I ask is because for the code below, if I delete default case, the code will provide error. Could someone please help me clarify the concept? Thanks in advance for any help!
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month"; //if delete will produce error
break;
}
System.out.println(monthString);
}
}
While the default
clause is not mandatory, if you remove it, monthString
may not be initialized, so you get a compilation error when you attempt to print it with System.out.println(monthString);
.
You can remove the default
clause if you give monthString
a default value when you declare it. For example :
String monthString = "Invalid month";
This will give the same behavior as your current switch statement, which includes the default clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With