gpt4 book ai didi

java - Java中int a[5],int a[],int a[]={2,3}的区别

转载 作者:行者123 更新时间:2023-12-01 07:48:19 24 4
gpt4 key购买 nike

我们如何静态声明数组?不可以是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.

关于java - Java中int a[5],int a[],int a[]={2,3}的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44958230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com