Hi, I am new to java and I need to work with arrays.
I have found some tutorials, but everywhere was something like

int[] anArray;

        // allocates memory for 10 integers
        anArray = new int[10];

But what if I dont know how long the array will be?
When I tried to do just that:

int[] anArray;

Without allocating memory, Im getting error:

The local variable anArray may not have been initialized.

Can you please help me?

4 Years
Discussion Span
Last Post by desup
Featured Replies
  • check the [URL="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html"]ArrayList class[/URL] or [URL="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html"]Vector class[/URL] Read More


you can initialize it as null, and then when you know how long will it be, you can assign a new array.

int[] myArray = null;

 //somwhere else at your code
 myArray = new int[10]; //or whatever your lenght will be

just be shure to access it after it is initialized, otherwise you will get NullPointerException.

P.S: Maybe you want to sign in, I'm designing a java online course :D

Edited by peter_budo: Keep It Spam-Free - Do not mention, plug or refer to any product, service, or website you are affiliated with

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.