Java OCA OCP Practice Question 657

Question

Which of the changes given in options can be done to let the following code compile and run without errors?

class Main{ // w  w  w. jav  a 2s .c om
   String s1 = "green mile";   // 0 
   public void m ( int n ){ 
      String local;   // 1 
      if ( n > 0 ) local = "good";   //2 
      System .out.println ( s1+" = " + local );   //3 
    } 
} 

Select 2 options 

A. Insert after line 2  : else local = "bad"; 
B. Insert after line 2  : if (n <= 0) local = "bad"; 
C. Move line  1 and place it after line 0. 
D. change line  1 to  :  final String local = "rocky"; 
E. The program already is without any errors. 



    Correct Options are  : A C

    Note

    The problem is that local is declared inside a method is therefore local to that method.

    It is called a local variable and it cannot be used before initialized.

    It will not be initialized unless you initialize it explicitly because local variables are not initialized by the JVM on its own.

    The compiler spots the usage of such uninitialized variables and ends with an error message.

    Making it a member variable will initialize it to null.

    Putting an else part will ensure that it is initialized to either 'good' or 'bad'.

    So this also works.




    PreviousNext

    Related