David Koplik David Koplik - 2 years ago 70
Java Question

Java - Define array size later

So I wanna make an array outside a method so other methods can use it:

public int x = 0;
public int[] myIntArray = new int[x];

But the x is 0, and is later defined in a method as a number entered by user:

x = input.nextInt();

But the method has already size 0, so how would I modify (redefine) the array's size? I tried to do it by defining the array in a method, but if I do that, I cannot access the array from another method. I am a beginner and I can't do ArrayList, is it possible to do this?

EDIT: Basically: How do I define the size of an array later?

Answer Source

Sure, just declare it where you have it with public int[] myIntArray; and then initialize it as soon as you know how big it has to be with myIntArray = new int[x];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download