Java OCA OCP Practice Question 601

Question

Which line, if any, will give a compile time error ?

void test (byte x){ 
   switch (x){ 
      case  'a':   // 1 
      case 256:   // 2 
      case 0:     // 3 
      default  :   // 4 
      case 80:    // 5 
    } 
} 

Select 1 option

  • A. Line 1 as 'a' is not compatible with byte.
  • B. Line 2 as 256 cannot fit into a byte.
  • C. No compile time error but a run time error at line 2.
  • D. Line 4 as the default label must be the last label in the switch statement.
  • E. There is nothing wrong with the code.


Correct Option is  : B

Note

A. is wrong

int value of 'a' can easily fit into a byte.

Every case constant expression in a switch block must be assignable to the type of switch expression.

For the following code:

byte by = 10; 
switch (by){ 
     300  :  //some code; 
     56  :   //some code; 
} 

This will not compile as 300 is not assignable to 'by' which can only hold values from - 128 to 127.

This gives compile time error as the compiler detects it while compiling.

The use of break keyword is not mandatory.




PreviousNext

Related