0

Why when I try to initialize the array like that it gives me an error

package practicejava;

class Test {

    public static void main(String[] args) {

        int[] array;
        array ={};

    }
}

Why the following code shows me an error?

Tiago Mussi
  • 803
  • 3
  • 12
  • 19
Tushar Mia
  • 245
  • 2
  • 6
  • 7
    Declaring and assigning an array this way, must take place within the same statement . – Arnaud Dec 20 '18 at 08:34
  • 1
    In short, because the language designers didn't allow this variation of intinalisation. – Peter Lawrey Dec 20 '18 at 08:51
  • @PeterLawrey Rather because they allow special syntax in initialization, where the stuff on the right hand side of the assignment isn't even a valid expression. The inconsistence appears because they allow too much, not because they didn't allow something. – Andrey Tyukin Dec 20 '18 at 09:59

3 Answers3

1

Change as follow:

int[] array;
array = new int[]{};

Your current way of assigning the array is invalid.

HaroldSer
  • 1,724
  • 2
  • 9
  • 17
  • 1
    or `array = new int[0];` – Peter Lawrey Dec 20 '18 at 08:50
  • While it is true, question is not *how* to get rid of error, but *why* we are getting it. – Pshemo Dec 20 '18 at 08:55
  • @Pshemo I stated it is invalid. – HaroldSer Dec 20 '18 at 08:56
  • But *why* is it invalid? Why does `int[] array = {1,2,3};` work fine while `int[] array;` `array = {1,2,3}` doesn't? What *logic* was used here? Compiler allows `array = new int[]{1,2,3}` (with explicit array type) but it also should know type of `array` variable, so it should be able to infer `int[]` part and add `new int[]` before `{1,2,3}` (which would result in `new []{1,2,3}` which compiles fine). – Pshemo Dec 20 '18 at 09:05
0

you have to declare array size in array like as below

   array  = new int[5];
avishka eranga
  • 85
  • 2
  • 11
0

The array needs to be declared on the same line of code as:-

int[] array = new int[]{...};

The first line of your code that is:-

int [] array = {...}

This line is allowed by Java and is just a shorthand notation for the above declaration. Note that, this is only allowed if the declaration and initialization of the array is done simultaneously (the allocation of array is handled internally and is done accordingly to the number of elements).

The line int [] array; just creates a reference in the stack which is null that is it doesn't point to anything.

But, when you do array = {...}, it is no longer valid as the memory needs to be allocated prior to initialization. Java does not handle such initialization internally. So, it is recommended to initialize array = new int[]{...} instead.