问题描述:

This is my code, after initialized the array, I cannot able to reassign some value in array. It shows array index out of bound exception.

public class NewClass {

public static void main(String args[]){

String cl[]={};

cl[0]="10";

System.out.print(cl.length);

}

}

my output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

at NewClass.main(NewClass.java:15)

Java Result: 1

网友答案:
String cl[]={};

Creates an instance of an empty array, so you can't add any elements to it.

In order to create a non empty array, use either

String cl[] = {"something",...};

or

String cl[] = new String[theArrayLength];
网友答案:

If you want to declare your array, you can do something like this:

String cl[];

After that you can initialize your array by calling this:

cl = new String[10];

And your System.out.print(cl.length); will return what you want.

相关阅读:
Top