Q:

How to declare an array without having to give a fixed initial size in java?

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

A:

Do it as follows:

Declare arr without any size and as an instance variable.
Initialize arr in the constructor with size entered by the user.

Also, it's better to have the condition for the for loop inside perform() as j < arr.length so that it depends purely on the size of arr and not on the value of i which might change in some other part of the program. For the same reason, I have declared i as a local variable inside the constructor so that its scope is limited to the constructor only (where it is required) and nowhere else.
Code:
import java.util.Scanner;

class Example {
    Scanner in = new Scanner(System.in);
    int[] arr;

    Example() {
        System.out.println("in constructor");
        System.out.println("enter array size: ");
        int i = in.nextInt();
        if (i >= 0) {
            arr = new int[i];
        }
    }

    void perform() {
        System.out.println("Enter " + arr.length + " integers");
        for (int j = 0; j < arr.length; j++)
            arr[j] = in.nextInt();
        for (int j = 0; j < arr.length; j++)
            System.out.println(arr[j]);
    }
}

public class Main {
    public static void main(String[] args) {
        Example obj = new Example();
        obj.perform();
    }
}

A sample run:
in constructor
enter array size: 
2
Enter 2 integers
10
20
10
20

