Grammar of the array

Suppose 'a' is an array variable.. int [] a = {1,3,2,4}; It works.

int [] a = new float [12];

a = {1,3,2,4}

I adjust like that to reduce the use of memories.. but it has grammatical error.

In this case, how can I solve this problem?

Do I have to type one by one like a[1] =1; a[2] = 3; ... ?

Thanks.

Tagged:

Answers

  • edited March 2017

    Creating an array w/ just {} only works when we're also declaring its variable at the same time.

    Using that special syntax, an array's length is determined by the number of elements inside its {}.

  • Answer ✓

    P.S.: We still can use {} after a variable has been declared.
    However, we need to fully specify the array's datatype this time:

    final int[] a; // declaration
    a = new int[] {1, 3, 2, 4}; // post-initialization
    

    Instead of declaration together w/ initialization:

    final int[] a = {1, 3, 2, 4}; // declaration + initialization
    
Sign In or Register to comment.