2

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
2
  • 1
    your cl array size is 0 and you trying to insert value so java.lang.ArrayIndexOutOfBoundsException you can go for dynamic list such as List<String> c1=new ArrayList<>(); Commented Oct 13, 2015 at 6:32
  • is possible to store array in list? Commented Oct 13, 2015 at 6:48

2 Answers 2

8
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];
Sign up to request clarification or add additional context in comments.

2 Comments

so what is the solution. ?
@Ram Use an ArrayList, if you need the "array" to be extensible.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.