Any shortcut to initialize all array elements to zero? - java

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;
}

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);

In java all elements(primitive integer types byte short, int, long) are initialised to 0 by default. You can save the loop.

How it Reduces the Performance of your application....? Read Following.
In Java Language Specification the Default / Initial Value for any Object can be given as Follows.
For type byte, the default value is zero, that is, the value of (byte) is 0.
For type short, the default value is zero, that is, the value of (short) is 0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types, the default value is null.
By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.
Because An array is a container object that holds a fixed number of values of a single type.
Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.
Now consider the array for String type so that all array elements has default value is null.
Why don't do that......?
you can assign null value by using loop as you suggest in your Question.
int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
arr[i] = 0;
But if you do so then it will an useless loss of machine cycle.
and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.
The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).

You can save the loop, initialization is already made to 0. Even for a local variable.
But please correct the place where you place the brackets, for readability (recognized best-practice):
int[] arr = new int[10];

If you are using Float or Integer then you can assign default value like this ...
Integer[] data = new Integer[20];
Arrays.fill(data,new Integer(0));

You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other.
Snipet:
package com.array.zero;
public class ArrayZero {
public static void main(String[] args) {
// Your array with data
int[] yourArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Creating same sized array with 0
int[] tempArray = new int[yourArray.length];
Assigning temp array to replace values by zero [0]
yourArray = tempArray;
//testing the array size and value to be zero
for (int item : yourArray) {
System.out.println(item);
}
}
}
Result :
0
0
0
0
0
0
0
0
0

Initialization is not require in case of zero because default value of int in Java is zero.
For values other than zero java.util.Arrays provides a number of options, simplest one is fill method.
int[] arr = new int[5];
Arrays.fill(arr, -1);
System.out.println(Arrays.toString(arr)); //[-1, -1, -1, -1, -1 ]
int [] arr = new int[5];
// fill value 1 from index 0, inclusive, to index 3, exclusive
Arrays.fill(arr, 0, 3, -1 )
System.out.println(Arrays.toString(arr)); // [-1, -1, -1, 0, 0]
We can also use Arrays.setAll() if we want to fill value on condition basis:
int[] array = new int[20];
Arrays.setAll(array, p -> p > 10 ? -1 : p);
int[] arr = new int[5];
Arrays.setAll(arr, i -> i);
System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4]

The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy:
static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);
This uses memcpy under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros concurrently, which doesn't hurt anything.
You could also use Arrays.fill as some others have mentioned. Arrays.fill could use memcpy in a smart JVM, but is probably just a Java loop and the bounds checking that entails.
Benchmark your optimizations, of course.

In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:
int arr[10] = {0};
But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
Arrays.fill(ar, 10);
System.out.println("Array completely filled" +
" with 10\n" + Arrays.toString(ar));
}
}

You defined it correctly in your question, it is nearly the same as for C++. All you need to do for the primitive data type is to initialize the array. Default values are for int 0.
int[] intArray = new int[10];

you can simply do the following
int[] arrayOfZeros= new int[SizeVar];

declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore

Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.

Yet another approach by using lambda above java 8
Arrays.stream(new Integer[nodelist.size()]).map(e ->
Integer.MAX_VALUE).toArray(Integer[]::new);

int a=7, b=7 ,c=0,d=0;
int dizi[][]=new int[a][b];
for(int i=0;i<a;i++){
for(int q=d;q<b;q++){
dizi[i][q]=c;
System.out.print(dizi[i][q]);
c++;
}
c-=b+1;
System.out.println();
}
result
0123456
-1012345
-2-101234
-3-2-10123
-4-3-2-1012
-5-4-3-2-101
-6-5-4-3-2-10

Related

Java arrays objects and initializer confusion

I'm learning java and was told arrays are implemented as objects. But they show two different codes without diving into details.
First they ask us to use arrays like this, but the downside is to manually add the values:
int nums[] = new int[10];
nums[0] = 99;
nums[1] = -622;
.
.
.
Then they use this in some programs saying new is not needed because Java automatically does stuff:
int nums[] = {99, - 10, 100123, 18, - 972 ......}
If the second code is shorter and allows me to use arrays straightaway whats the point of the first code if they do the same thing but the first one require more code to input value by hand.
Let's say you were initializing an array of 1 million values, would you use the second method? No, because you would have a huge java file.
The first method is essentially allocating space:
int[] array = new int[1000000];
Creates 1 million spaces in memory with default value 0. Now if you want to initialize them, you may use a loop:
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
If you wanted an array of 10 million values, you only change one number:
// Just add a 0 to 1000000
int[] array = new int[10000000]
Now, if the size of your array changes, you don't have to change the loop. But if you used the second method and wanted an array of 10 million values, you would have to add 9 million values, and 9 million commas to your java file - not scalable.
int[] array = {1, 2, 3, 4, ... 1000000};
The second method is not "scalable." It only works for small arrays where you can confidently assume that the default values of that array won't change. Otherwise, it makes A LOT more sense to use the first (more common) method.
//This is one way of declaring and initializing an array with a pre-defined size first
int nums[] = new int[10];
//This is initializing the array with a value at index 0
nums[0] = 99;
//This is initializing the array with a value at index 1 and likewise allocating rest of array index values
nums[1] = -622;
//This is another way of declaring and initializing an array directly with pre-defined values. Here if you see instead of declaring array size first, directly the values are initialized for it
int nums[] = {99, - 10, 100123, 18, - 972 ......}
It depends on the way you prefer to use the arrays, but you must remember that whenever you use "new" keyword, there is a new space or resource created every time in memory.
When you don't know the items of array at the time of array declaration, then prefer method-1,
and,
when you know the all the values of array at the time of array declaration, then go for method-2
Imagine you want to generate a series of random integers at runtime and want to store in the array:
int[] array = new int[1000000];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt();

Adding two integer arrays

I have done some searching for this, however I haven't found anything specific to what I'm working on.
I'm trying to do addition with two arrays of integers. This alone isn't difficult, however, I'm having difficulty with a specific aspect.
The array size and array elements are determined by user input. Each digit must be greater than or equal to 0 and less than or equal to 9. The problem lies in the fact that if I initialize an array in my method, I must determine the size of the array when I initialize it. But if the user enters a series of numbers, such as 8, 0, 0, 0 for the first array, and 3, 0, 0, 0 for the second array, that would result in the sum[] being one integer bigger than either of the arrays initialized by the user. I don't want to do
int[] sum = new int[x.length+1]
because in the case of it not needing an extra element, I will get an ugly 0 where I don't want to see that. I'm not necessarily asking for a direct answer with code, but perhaps a bit of wisdom that will push me in the right direction. Thanks.
public static int[] addArrays(int[] x, int[] y){
int[] sum = new int[?];
int carryOver = 0;
int singleDigit = 0;
Just make the array originally the same size as the original (int[] sum = new int[x.length];. Then, if you need to expand the size of your array, set sum =Arrays.copyOf(sum, sum.length+1);, which will expand the size of your array to the necessary size.

Multidimensional array declaration

Which one is valid statement?
int[] x =new int[0]{};
new int[2];
int[] x=new int[][]{{1}}[0];
int[][] x = new int[]{0}[0][0];
int x= new int[2]{}[];
The correct answer is 3, and I can understand why it's not 1, 2 or 5, but I don't understand 3 or 4 mean.
1) int[] x =new int[0]{};
You cannot specify both a length 0 and an array initializer at the same time.
2) new int[2];
It's not a statement. It would become a statement if it were assigned to something else, among other possibilities.
3) int[] x=new int[][]{{1}}[0];
This declares and initializes a 1x1 2D array, with 1 being its only element. Then, array access is used to immediately access the "row" at position 0, the only such "row", which is itself a 1-length 1D array, and that is assigned to a 1D array.
4) int[][] x = new int[]{0}[0][0];
There is a lot wrong here. A 1-length, 1D array is created, but there are two array accesses on it. You can only supply one, because it's a 1D array.
5) int x= new int[2]{}[];
The extra [] doesn't do anything and is invalid syntax. Even if they're removed, you can't assign an int array to a scalar int. Also you can't specify a length and an array initializer {} at the same time.
When you declare and initialize an array using {} you are not allowed to indicate the number of items in the array ergo int[0] should be int[]. So it should have been int[] x = new int[]{}.
This is an initialization without a declaration so it should have been something like int[] x = new int[2].
This is correct because it assigns a declaration to an item of two-dimensional array which is an array itself. So the array returned from new int[][]{{1}}[0] is new int[]{1} and thus int[] x = new int[]{1}.
This is totally wrong and messed up. new int[]{0}[0][0] is trying to get a value of a two-dimensional array from a one-dimensional array and assign that to a the array x.
Here as discussed already in point 1, plus trying to access an array with an empty index [] which not possible.

Initializing an array after the declaration

Why we cannot use array intializer after declaring an variable.
For example:
int arr[];
arr = {1,2,3,4};
But,
int arr[] = {1,2,3,4};
is correct.
Is there any way to use array initialize after declaring an variable.
This is how you can.
int arr[];
arr = new int[]{1, 2, 3, 4};
There are three steps to creating an array, declaring it, allocating it and initializing it.
Declaring Arrays
Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.
Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:
int[] k;
float[] yt;
String[] names;
In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.
Allocating Arrays
Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above:
k = new int[3];
yt = new float[7];
names = new String[50];
The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. Therefore this step is sometimes called dimensioning the array. More commonly this is called allocating the array since this step actually sets aside the memory in RAM that the array requires.
This is also our first look at the new operator. new is a reserved word in java that is used to allocate not just an array, but also all kinds of objects. Java arrays are full-fledged objects with all that implies. For now the main thing it implies is that we have to allocate them with new.
Initializing Arrays
Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException.
You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.
Here's how we'd store values in the arrays we've been working with:
k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};
see http://www.cafeaulait.org/javatutorial.html#xtocid499429
Because an array doesn't work like that in java.
int arr[4];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
Check this
example :-
int data[] = new int[] {10,20,30,40,50,60,71,80,90,91 };
or
int data[];
data=new int[] {10,20,30,40,50,60,71,80,90,91 };

How to initialize all the elements of an array to any specific value in java

In C and C++ we have the memset() function which can fulfill my wish. But in Java, how can I initialize all the elements to a specific value?
Whenever we write int[] array = new int[10], this simply initializes an array of size 10 having all elements set to 0, but I just want to initialize all elements to something other than 0 (say, -1).
Otherwise I have to put a for loop just after the initialization, which ranges from index 0 to index size − 1, and inside that loop assign each element to the desired value, like this:
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = -1;
}
Am I going correct? Is there any other way to do this?
If it's a primitive type, you can use Arrays.fill():
Arrays.fill(array, -1);
[Incidentally, memset in C or C++ is only of any real use for arrays of char.]
There's also
int[] array = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
It is also possible with Java 8 streams:
int[] a = IntStream.generate(() -> value).limit(count).toArray();
Probably, not the most efficient way to do the job, however.
You could do this if it's short:
int[] array = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
but that gets bad for more than just a few.
Easier would be a for loop:
int[] myArray = new int[10];
for (int i = 0; i < array.length; i++)
myArray[i] = -1;
Edit: I also like the Arrays.fill() option other people have mentioned.
java.util.Arrays.fill()
Have you tried the Arrays.fill function?
You can use Arrays.fill(array, -1).
Using Java 8, you can simply use ncopies of Collections class:
Object[] arrays = Collections.nCopies(size, object).stream().toArray();
In your case it will be:
Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.
Here is a detailed answer of a similar case of yours.
Arrays class in java.utils has a method for that.
Arrays.fill(your_array, value_to_fill);
Evidently you can use Arrays.fill(), The way you have it done also works though.
For Lists you can use
Collections.fill(arrayList, "-")

Categories