我可以初始化方法之外的数组,就像我们初始化成员/字段变量一样

Sal*_*han 2 java

我想在实例级别初始化数组,但我无法在这里初始化代码

public class Arrays {

    /** Creates a new instance of Arrays */

        int []arr2=new int[2];
        arr2[0]=20;//error at compile time
        arr2[1]=30;//error 


    public Arrays() {        }
    public static void main(String []args)
    {
        System.out.println("Element at 0th position is "+arr2[0]);
        System.out.println("Element at 1th position is "+arr2[1]);
    }


}
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 6

如果你想在宣布它为类成员的同时进行初始化,就这样做

class MyClass{
    int []arr2={20,30};
}  
Run Code Online (Sandbox Code Playgroud)

以下是一个声明,你不能在你想要做的地方写声明

arr2[0]=20;//error at compile time
Run Code Online (Sandbox Code Playgroud)


Ara*_*ram 5

这是初始化的方法

int[] arr2 = { 20, 30 };
Run Code Online (Sandbox Code Playgroud)