In C/C++
I used to do
int arr[10] = {0};
...to initialize all my array elements to 0.
Is there a similar shortcut in Java?
I want to avoid using the loop, is it possible?
int arr[] = new int[10]; for(int i = 0; i < arr.length; i++) { arr[i] = 0; }
Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.
Using default values in initialization of array For double or float , the default value is 0.0 , and the default value is null for string. Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};
A default value of 0 for arrays of integral types is guaranteed by the language spec:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type
int
, the default value is zero, that is,0
.
If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).
While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arrays class:
int [] myarray = new int[num_elts]; Arrays.fill(myarray, 42);
Or if you're a fan of 1-liners, you can use the Collections.nCopies()
routine:
Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);
Would give arr the value:
[42, 42, 42]
(though it's Integer
, and not int
, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive()
routine:
int [] primarr = ArrayUtils.toPrimitive(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With