Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer array static initialization

Which two code fragments correctly create and initialize a static array of int elements? (Choose two.)

A.

static final int[] a = { 100,200 };

B.

static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }

C.

static final int[] a = new int[2]{ 100,200 };

D.

static final int[] a;
static void init() { a = new int[3]; a[0]=100; a[1]=200; }

Answer: A, B

here even D seems true, can anyone let me know why D is false.

like image 798
user516108 Avatar asked Dec 15 '10 12:12

user516108


People also ask

What is static array initialization?

It is initialized only once, the first time the control passes through its declaration. 3. If a static array is not explicitly initialized, its elements are initialized with the default value which is zero for arithmetic types (int, float, char) and NULL for pointers.

Are static arrays initialized to zero?

If your array is declared as static or is global, all the elements in the array already have default default value 0. Some compilers set array's the default to 0 in debug mode.

Is an int array initialized to 0?

Please note that the global arrays will be initialized with their default values when no initializer is specified. For instance, the integer arrays are initialized by 0 . Double and float values will be initialized with 0.0 . For char arrays, the default value is '\0' .

Can we declare array as static?

Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.


2 Answers

The correct answers are 1 and 2 (or A and B with your notation), and an also correct solution would be:

static final int[] a = new int[]{ 100,200 };

Solution D doesn't initalize the array automatically, as the class gets loaded by the runtime. It just defines a static method (init), which you have to call before using the array field.

like image 196
buc Avatar answered Oct 15 '22 12:10

buc


D defines a static method for initialising a but does not actually call it. Thus, a remains uninitialised unless someone explicitly calls the init method.

As other answers have pointed out: D shouldn't even compile because it attempts to assign a value to the final variable a. I guess that's a much more correct explanation. Nevertheless, even if a was not final D would still not work without extra code.

I assume the new int[3] in D is a typo? The other three all attempt to create an array of length 2.

like image 37
Cameron Skinner Avatar answered Oct 15 '22 13:10

Cameron Skinner