ICSE Class 10 Computer Applications Question 16 of 43

Conditional Constructs in Java — Question 16

Back to all questions
16
Question

Question 16

Find the errors in the following code and rewrite the correct version:

char m="A";
Switch ("A");
{
 Case 'a';
     System.out.println("A");
     break;
 Case 'b';
     System.out.println("B");
     break;
 Default:
     System.out.println("Not a valid option");
}
Answer

The code has the following errors:

  1. char variable m is assigned a String literal.
  2. S in Switch is capital.
  3. There should be no semicolon (;) after switch statement.
  4. Expression of switch statement is a String literal "A".
  5. C in Case is capital.
  6. Semicolon (;) of case statements should be replaced with colon (:).
  7. D in Default is capital.

Corrected Version:

char m = 'A';
switch (m) {
  case 'a':
    System.out.println("A");
    break;
  case 'b':
    System.out.println("B");
    break;
  default:
    System.out.println("Not a valid option");
}