Home > Blockchain >  Why am I getting an error when declaring an empty array and entering a value as below
Why am I getting an error when declaring an empty array and entering a value as below

Time:07-24

public class ArrayTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int number[] = { , };
        number[0]=1;
        number[1]=2;
        
    }

}

> Exception in thread "main" java.lang.Error: Unresolved compilation
> problem:      Array constants can only be used in initializers
> 
>   at test.ArrayTest.main(ArrayTest.java:8)

The part that declares an empty array is given in the problem. I don't know how to assign a value to this part.

The declaration part of an array cannot be modified.

CodePudding user response:

There are many ways to create an initialize an array. Using { } is one way but you provide the values.

For example:

int number[] = { 0, 0};

CodePudding user response:

The int number[] = { , }; will create an empty array. Not a null array. So the array will exist, but will have 0 elements.

Here are 2 possible ways you can do what you want:

public class ArrayTest {

    public static void main(final String[] args) {
        // TODO Auto-generated method stub
        final int number[] = { 1, 2 };
        number[0] = 1;
        number[1] = 2;
    }

    public static void main2(final String[] args) {
        // TODO Auto-generated method stub
        final int number[] = new int[2];
        number[0] = 1;
        number[1] = 2;
    }

}
  • Related