What restrictions placed on values of each case of a switch statement ?
Answer : Switch statement is Java language is a multiple branch statement and It provides a way to dispatch execution to different parts of the code based on provided the value of an expression. It also provides a better alternative approach than a large series of if-else-if statements.
Restriction : When we compile java program the values of every case of a switch statement will be evaluated to a value that can be promoted to an int value or not. Below is example of switch statement :
package com.javahonk.switchtest; public class SwitchTest { 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"; break; } System.out.println(monthString); } }
Output:
Check season using switch statement :
package com.javahonk.switchtest; public class SwitchTest { public static void main(String args[]) { int month = 8; String season; switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus Month"; } System.out.println("August is in the " + season + "."); } }
Output :
Nested switch statement example :
package com.javahonk.switchtest; public class NestedSwitchTest { public static void main(String args[]) { int month = 1; String season = null; switch (month) { //nested switch case 1: switch (month) { case 12: case 1: case 2: season = "Winter"; break; case 3: case 4: case 5: season = "Spring"; break; case 6: case 7: case 8: season = "Summer"; break; case 9: case 10: case 11: season = "Autumn"; break; default: season = "Bogus Month"; } break; case 2: // ... case 3: // ... } System.out.println("January is in the " + season + "."); } }
Output :