Why do we have null array declaration in java -


int[] numbers; 

i cannot use numbers array after declaring above without initializing. gone through steps of using it. tried assign values, used fill , tried length , came conclusion it's wrong way declare array, don't understand why java has such syntax. it's confusing.

why? because need initialize array based on conditional runtime information:

void syntheticexample(int[] these, int[] those, int[] theothers) {     int[] numbers;      // ...some work...      if (/*...some condition...*/) {         numbers = these;     } else {         // ...more work, then:         if (/*...some other condition...*/) {             numbers = those;         } else if (/*...some further condition...*/) {             numbers = theothers;         } else {             // we'll use our own numbers             numbers = new int[] {1, 2, 3};         }     }      // ...use `numbers`... } 

it's same reason can declare other kind of variable without initializing it. declaration , initialization/assignment different things, , need happen @ different times.


and jean-baptiste's distinction useful , important here: numbers in above variable, contains object reference. refers to array (or nothing, if assign null it).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -