On this page, we will learn about switch cases in Java. What is a switch case in Java? , Switch Case Syntax in Java: What is Switch Case in Java? Switch Case Example with int in Java, Switch Case Example with char in Java, Switch Case is fall-through in Java; Nested Switch Case syntax in Java; and Nested Switch Case Example in Java.
The Java switch case statement in java conducts one statement from multiplex agreements. It is like if-else-if ladder assertion. The switch case statement pursuits with byte, short, int, long, enum types, String and few wrapper types like Byte, Short, Int, and Long. Since Java 7, you will be able to use strings in the switch statement.
In another words, the switch case statement tests the equilibrium of a variable opposed to multiple values.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
default:
//if all cases are not matched;
}
import java.io.*;
public class Example {
public static void main(String[] args) {
int month = 2;
switch(month){
case 1:
System.out.println("First Month");
break;
case 2:
System.out.println("Second Month");
break;
default:
System.out.println("Invalid Month!");
}
}
}
Second Month
import java.io.*;
public class Example {
public static void main(String[] args) {
char letter = 'a';
switch(letter){
case 'a':
System.out.println("This is a");
break;
case 'b':
System.out.println("This is b");
break;
default:
System.out.println("Invalid!");
}
}
}
This is a
The Java switch statement is fall-through. It suggests that it executes all statements after the primary match when a break statement is not at hand.
import java.io.*;
public class Main {
public static void main(String args[]){
int age = 1;
switch(age){
case 1:
System.out.println("1 Year");
case 2:
System.out.println("2 Years");
default:
System.out.println("Invalid Age!");
}
}
}
1 Year
2 Years
Invalid Age!
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//Nested Switch Case
switch(expression2){
case value1:
//code to be executed;
break; //optional
default:
//if all cases are not matched;
}
break; //optional
default:
//if all cases are not matched;
}
import java.io.*;
public class Main {
public static void main(String args[]){
int age = 1;
int month = 2;
switch(age){
case 1:
switch(month){
case 1:
System.out.println("Age 1, Month 1");
break;
case 2:
System.out.println("Age 1, Month 2");
break;
default:
System.out.println("Invalid age,Month!");
}
break;
case 2:
System.out.println("2 Years");
break;
default:
System.out.println("Invalid Age!");
}
}
}
Age 1, Month 2