We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Array withou allocating memory?

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?

3
Contributors
3
Replies
33 Minutes
Discussion Span
1 Year Ago
Last Updated
4
Views
Question
Answered
desup
Light Poster
25 posts since Jan 2012
Reputation Points: 10
Solved Threads: 5
Skill Endorsements: 0
zeroliken
Nearly a Posting Virtuoso
1,346 posts since Nov 2011
Reputation Points: 214
Solved Threads: 205
Skill Endorsements: 14

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
<URL SNIPPED>

RicardoE
Junior Poster in Training
73 posts since Jan 2010
Reputation Points: 21
Solved Threads: 7
Skill Endorsements: 0
Question Answered as of 1 Year Ago by RicardoE and zeroliken

check the ArrayList class or Vector class

Yeah, ArrayList helped.. thank you :)

desup
Light Poster
25 posts since Jan 2012
Reputation Points: 10
Solved Threads: 5
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0659 seconds using 2.72MB