Computer Applications
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");
}
Answer
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.
Related Questions
Rewrite the following code using single if statement.
if(code=='g') System.out.println("GREEN"); else if(code=='G') System.out.println("GREEN");Evaluate the given expression when the value of a=2 and b=3
b*=a++ - ++b + ++a; System.out.println("a= "+a); System.out.println("b= "+b);How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }