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
static void setSize(int i) { size = i; x[] = new int[size]; }Java Result: 1coming from?