default statement in Java Switch Case
default case in the Switch case specifies what code to run if no case matches.
It is preferred to write the default case at the end of all possible cases, but it can be written at any place in switch statements.
Example:
Writing default in the middle of switch statements:
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
int i=2;
switch(i){
default:
System.out.println("Default");
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
}
}
Output
2 3
Example:
Writing default in starting of switch statements
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
switch (i) {
default:
System.out.println("Default");
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
}
}
Output
Default 1
Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short, char, or int primitive data type. It tests the equality of variables against multiple values.