Java OCA OCP Practice Question 1465

Question

Consider the following program:

public class Main {
   public static void main(String[] args) {
      calculate(2);// w w w.ja  va  2 s.  co  m
   }

   public static void calculate(int x) {
      String val;
      switch (x) {
      case 2:
      default:
         val = "def";
      }
      System.out.println(val);
   }
}

What will happen if you try to compile and run the program?

Select 2 options

  • A. It will not compile saying that variable val may not have been initialized..
  • B. It will compile and print def
  • C. As such it will not compile but it will compile if calculate (2); is replaced by calculate (3);
  • D. It will compile for any int values in calculate (...);


Correct Options are  : B D

Note

When you try to access a local variable, the compiler makes sure that it is initialized in all the cases.

If it finds that there is a case in which it may not be initialized then it flags an error.

For example:

int i; 
if ( somecondition) 
   i = 20; 
int k = i; 

If some condition returns false, then i remains uninitialized hence the compiler flags an error.




PreviousNext

Related