This question already has answers here:
Array initialisation in java
                                
                                    (5个答案)
                                
                        
                2年前关闭。
            
        

我们如何静态声明数组? int a[5];不能吗?

package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}

最佳答案

考虑以下情形

// Create new array with the following two values
int a[] = {1,9};
Assert.assertTrue( 2 == a.length );
Assert.assertTrue( 1 == a[0] );
Assert.assertTrue( 9 == a[1] );

// Create a new, uninitialized array
int[] a;
Assert.assertTrue( null == a );
Assert.assertTrue( 0 == a.length ); // NullPointerException

int a[9]; // this will not compile, should be
int a[] = new int[9];
Assert.assertTrue( 9 == a.length );
Assert.assertTrue( null == a[0] );

// Provided 'a' has not been previously defined
int a[];
a[0] = 10; // NullPointerExcpetion

// Provided 'a' has been defined as having 0 indicies
int a[] = new int[0];
a[0] = 10; // IndexOutOfBoundsException

// Provided 'a' has been defined as an empty array
int a[] = new int[1];
a[0] = 10; // Reassign index 0, to value 10.

09-25 22:04
查看更多