W3docs

Java Initialize an int array in a constructor

To initialize an int array in a constructor in Java, you can use an initializer list as follows:

To initialize an int array in a constructor in Java, you can use an initializer list as follows:


public class MyClass {
  private int[] arr;

  public MyClass(int size) {
    arr = new int[size];
  }
}

This creates an int array with the specified size and assigns it to the arr field.

You can also initialize the array with a set of values using varargs:


public class MyClass {
  private int[] arr;

  public MyClass(int... values) {
    arr = values;
  }

  public int[] getArr() {
    return arr;
  }
}

This assigns the values array directly to the arr field.

You can then use the array in your class as follows:


MyClass obj = new MyClass(1, 2, 3, 4, 5);
int[] arr = obj.getArr();

This creates a new MyClass object with an int array containing the values 1, 2, 3, 4, and 5, and assigns it to the arr field. You can access the array using the getArr method.

Note that in this example, the int array is marked as private, which means that it can only be accessed within the MyClass class. We provided a getArr getter method to allow external access while maintaining encapsulation.