- A switch case is a control statement that lets you run different blocks of code based on the value of a variable or expression.
- It’s often cleaner and easier to read than writing many if–else statements.
- It allows only the local variable.
- We use break; to stop the execution after the expected result is executed. Intead of break; we can use ->. ex: case 1: System.out.println("Monday"); break; instead of this we can use below(from java 12th version) case 1 -> System.out.println("Monday");
- In the primitive data types it allows only int, byte, short, char.
-
It allows non-primitive data type String(from java 8 released) .
Example-1:
public static void main(String[] args) {int day=5;//primitive data type - it allows only int, byte, short, char
//non-primitive data type - it allows Stringswitch (day) //Expression { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Holiday"); }}
}
Example-2:
package moduleTwo;
public class SwitchCaseTest {
public static void main(String[] args) {
String say="hello";
switch (say) //Expression
{
case "hi":
System.out.println("hey");
break;
case "hello":
System.out.println("Good morning");
break;
default:
System.out.println("unknown");
}
}
}
Example-3:
public class SwitchCaseTest {
public static void main(String[] args) {
String grade="B";
switch (grade) //Expression
{
case "A","B" ->System.out.println("pass");
case "C" -> System.out.println("fail");
default -> System.out.println("no result");
}
}
}
Top comments (0)