KnowledgeBoat Logo

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");
}

Java Conditional Stmts

ICSE Sp 2025

8 Likes

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 an enum.

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.

Answered By

3 Likes


Related Questions