How to add multiple values to array within class?

Yes. 1st example is your fixed code. While 2nd 1 is an alternative using variable arguments.

The statement this.myArray = new int[4]; is correct.

However the following myArray = val1, val2, val3, val4; isn’t valid Java syntax!

Once a Java array is created we’d have to initialize each index 1 by 1:

  Foo(int val1, int val2, int val3, int val4) {
    myArray = new int[4];

    myArray[0] = val1;
    myArray[1] = val2;
    myArray[2] = val3;
    myArray[3] = val4;
  }

Therefore my recommendation is to go w/ either of my 2 examples for a shorter code.

More about Java array creation & initialization:

1 Like