Java switch case is like if..else statement, it also executes only one block of code from multiple blocks of code present. The data type that can be used to control the switch statement are int, byte, short, char, long and from Java 7 a String literal constant can also be used to control a switch statement.
Some important points about switch cases in Java.
- We can have N number of switch-case statements in Java.
- Duplicate values are not allowed or we will get a compilation error.
- Data of the value which we provide to the switch case must be the same as the data type of the expression of the switch case.
- The datatype which is allowed for switch case expression is int, char, short, byte, and long.
- Break statement in switch case is to control execution if we remove break then it will execute all the code until it reaches its end or meets new break statement.
- The default statement is optional, it gets execute when no expression matches the case. If we remove the default statement then noting will execute in that case.
Example: Write a Java program to print the month name base on the given number.
public class Main
{
public static void main(String[] args) {
int monthNumber = 12;
switch(monthNumber) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Not a valid month number!!");
}
}
}
Output:
December
Example: Write a Java program to print the season name based on the given month number.
- Spring - March, April, May
- Summer - June, July, August
- Autumn - September, October, November
- Winter - December, January, February
public class Main
{
public static void main(String[] args) {
int monthNumber = 12;
switch(monthNumber) {
case 3:
case 4:
case 5:
System.out.println("Spring Season!!!");
break;
case 6:
case 7:
case 8:
System.out.println("Summer Season!!!");
break;
case 9:
case 10:
case 11:
System.out.println("Autumn Season!!!");
break;
case 12:
case 1:
case 2:
System.out.println("Winter Season!!!");
break;
default:
System.out.println("Not a valid month number!!");
}
}
}
Output:
Winter Season!!!
No comments:
Post a Comment