OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Part:16 - Switch Statement
Java switch Statement
The switch statement in Java is a multi-branch conditional statement that executes one block of code out of many options based on the value of a variable or expression.
It is an alternative to using multiple if-else-if statements when checking for equality.
Syntax of switch Statement
🔑 Key Points:
-
The expression must evaluate to one of the following types:
-
byte,short,int,char,String, or anenum
-
-
casevalues must be unique constants or literals (not variables). -
breakprevents fall-through (execution of the next case). -
defaultis optional and runs when no case matches.
🔸 Example 1: Simple Day Selector
📤 Output:
Wednesday
🔸 Example 2: Switch with String
📤 Output:
Mango is sweet.
🔸 Example 3: Switch without break (Fall-through Behavior)
📤 Output:
⚠️ Explanation: No break → executes all following cases.
Example 4: Calculator using switch
Comments
Post a Comment