Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why after initializing the array I cannot assign some value in array?

Tags:

java

arrays

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
like image 488
Revatha Ramanan K Avatar asked Jun 26 '26 05:06

Revatha Ramanan K


1 Answers

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];
like image 108
Eran Avatar answered Jun 27 '26 19:06

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!