Ski
Ski

Reputation: 111

Declaring an array size of an instance array in a method

I'm trying to declare the array size of the instance array in a method. Is there any way to do it? Thank you.

package javaapplication2;

public class JavaApplication2 {

static int size;
static int x[] = new int[size];

public static void main(String[] args) {

    setSize(5);
    for (int i = 0; i < 5; i++) {
        x[i] = i;
    }

}

static void setSize(int i) {

    size = i;

}

}

Here's the updated codes. I'm getting an array out of bounds error. I'm assuming because the size did not get declared even like this:

package javaapplication2;

public class JavaApplication2 {

static int x[];

public static void main(String[] args) {

    setSize(5);
    for (int i = 0; i < 5; i++) {
        x[i] = i;
    }

}

static void setSize(int i) {

    x = new int[i];

}

}

I'm getting this error. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at javaapplication2.JavaApplication2.main(JavaApplication2.java:13) Java Result: 1

Upvotes: 2

Views: 1294

Answers (3)

Anderson Vieira
Anderson Vieira

Reputation: 9049

When your code is executed it runs somewhat like this:

  1. The line static int size declares the variable size and sets its value to 0, which is the default value for int.
  2. When you do static int x[] = new int[size] the value of size is 0. So x[] is initialized as an array of size 0. This all happens before main() gets called.
  3. Later, when you change size value to 5, it has no effect on the size of the x array, since it was already initialized.

You have two options in this case:

  • Set size to 5 when you declare it: static int size = 5,

or

  • Initialize x[] only after calling setSize():

    static int size;
    static int x[];
    
    public static void main(String[] args) {
        setSize(5);
        x = new int[size];
        ...
    }
    

Upvotes: 1

Mordechai
Mordechai

Reputation: 16204

Global variables are initialized before any constructor or the main method, therefore size is declared to 0 by default at the time the array is initialized.

Setting size to 5 won't help changing the already initialized array.

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213203

Initialize the array also in the setSize() method, and remove the initializer from the place of declaration.

static int size;
static int[] x;

static void setSize(int i) {
    size = i;
    x = new int[i];
}

Upvotes: 1

Related Questions