Java OCA OCP Practice Question 1425

Question

Which of the following are correct ways to initialize the static variables MAX and myString?

class Widget{ //from   w  w w .  ja va  2 s  . c o  m
   static int MAX;     //1 
   static final String myString;   // 2 
   Widget (){ 
       //3 
    } 
   Widget (int k){ 
       //4 
    } 
} 

Select 2 options

A. Modify lines // 1 and //2 as  : 
  
  static int MAX = 111; 
  static final String myString = "XYZ123"; 

B. Add the following line just after //2  : 
   static  {  //  ww  w  .  j  a  v a 2  s . c  o  m
      MAX = 111; 
      myString = "XYZ123";  
   } 

C. Add the following line just before // 1  :  
   { 
       MAX = 111; 
       myString = "XYZ123";  
   } 

D. Add the following line at //3 as well as //4  : 
   
   MAX = 111; 
   myString = "XYZ123"; 
   
E. Only option 3 is valid. 


Correct Options are  : A B

Note

static variables can be left without initializing. They will get default values.

final variables must be explicitly initialized.

Now, here myString is a 'static final' variable and not just final or static.

static fields can be accessed even without creating an instance of the class.

It is possible that this field can be accessed before even a single instance is created.

In this case, no constructor or non-static initializer had ever been called.

The field remains uninitialized.

This causes the compiler to complain.




PreviousNext

Related