1

I want to create an int array with 999 elements, each of which has value 999. Is there a way to initialize an int array during declaration instead of iterating through each element and setting its value to 999?

1

3 Answers 3

5

If the array was small, e.g. only 3 items, you could do as follows::

int[] ints = { 999, 999, 999 };

But if it grows and you don't want to repeat yourself, then better use Arrays#fill(). It hides the for loop away for you.

int[] ints = new int[999];
Arrays.fill(ints, 999);
Sign up to request clarification or add additional context in comments.

1 Comment

This uses a for loop for you. You can create a helper method which will create a new array filled with a value.
2

This is not possible as you ask, you can however use Arrays.fill() to fill it and use an initialiser block to call that method:

class MyClass {
    private int [] myInts = new int[999];

    {
        Arrays.fill(myInts, 999);
    }

    // ...
}

Comments

2

Of course, it is:

int[] tab = {999, 999, 999, 999, 999, 999, 999, 999, 999, 999, ... };

You just have to type 999 for the number of elements you want, in this case 999 times)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.