2(iii)
A student executes the following program segment and gets an error. Identify the statement which has an error, correct the same to get the output as WIN.
boolean x = true;
switch(x)
{
case 1: System.out.println("WIN"); break;
case 2: System.out.println("LOOSE");
}Show SolutionHide Solution↓
Statement having the error is:
boolean x = true;
Corrected code:
int x = 1; // Change boolean to int
switch(x)
{
case 1: System.out.println("WIN"); break;
case 2: System.out.println("LOOSE");
}
Explanation:
The error occurs because the switch statement in Java does not support the boolean data type. A switch expression must be one of the following types:
int,byte,short,char,String, or anenum.
Replacing boolean x = true; with int x = 1; ensures that the switch statement now uses a valid data type (int). Assigning x = 1 makes the case 1 to execute printing WIN as the output.