Java Switch StatementThe Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement. In other words, the switch statement tests the equality of a variable against multiple values. Points to Remember
Syntax: Flowchart of Switch Statement Example: SwitchExample.java Test it NowOutput: 20 Finding Month Example: SwitchMonthExample.javaHTML Test it NowOutput: 7 - July Program to check Vowel or Consonant: If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive. SwitchVowelExample.java Output: Vowel Java Switch Statement is fall-throughThe Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present. Example: SwitchExample2.java Test it NowOutput: 20 30 Not in 10, 20 or 30 Java Switch Statement with StringJava allows us to use strings in switch expression since Java SE 7. The case statement should be string literal. Example: SwitchStringExample.java Test it NowOutput: Your Level is: 3 Java Nested Switch StatementWe can use switch statement inside other switch statement in Java. It is known as nested switch statement. Example: NestedSwitchExample.java Test it NowOutput: Data Communication and Networks, MultiMedia Java Enum in Switch StatementJava allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma. Example: JavaSwitchEnumExample.java Test it NowOutput: Sunday Monday Twesday Wednesday Thursday Friday Saturday Java Wrapper in Switch StatementJava allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement. Example: WrapperInSwitchCaseExample.java Test it NowOutput: You are eligible for vote. Next TopicJava For Loop |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India