I'm trying to declare an array without having to give a fixed initial size, cause I want to accept the size from the user. Here's the latest method I came up with. I could give a maximum accepted value while declaring but I don't want to do that as it's a poor use of space.
class Example{
int i;
Scanner in = new Scanner(System.in);
Example(){
System.out.println("in constructor");
System.out.println("enter array size: ");
i = in.nextInt();
}
int[] arr = new int[i];
void perform(){
for(int j=0;j<i;j++)
arr[j] = in.nextInt();
for(int j=0;j<i;j++)
System.out.println(arr[j]);
}
}
public class Main{
public static void main(String[] args){
Example obj = new Example();
obj.perform();
}
}
The output is like this:-
in constructor
enter array size:
5
1 // This is me trying to enter the first element of the array.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0