Define the concept of multi-way decision-making using the switch statement in Java.
Advertisements
Question
Define the concept of multi-way decision-making using the switch statement in Java.
Code Writing
Definition
Advertisements
Solution
Multi-way decision-making using the switch statement in Java is a process that allows a program to select and execute one block of code from several alternatives based on the value of an expression. It is useful when a program needs to choose among multiple possible options.
Working of the switch Statement:
- The
switchstatement evaluates an expression and compares its value with differentcaselabels. - If a matching
caseis found, the statements associated with that case are executed. - The
breakstatement terminates theswitchblock and prevents the execution of subsequent cases. - If no matching case is found, the
defaultblock is executed, if present.
Example Program:
class SwitchExample
{
public static void main(String[] args)
{
int day = 2;
switch (day)
{
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("Invalid Day");
}
}
}
Output:
Tuesday
shaalaa.com
Is there an error in this question or solution?
