Different ways to initialize array in java

Array Initialize

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Each item in the array can be accessed with its index very efficiently. In this post we examine different ways to create and initialize arrays in java
Creating array of specific size and populating using for loop
We create a new int array of size 10 and set values using for loop.
//initialize array of size 10 of type int
int rollNums[] = new int[10];
//iterate from 0 to the last index of the array and set values
for (int i = 0; i < rollNums.length; i++) {
      rollNums[i] = i + 1;
}
Assigning value while creating the array.
Here we create a new int array and pass the values in the curly braces.
int rollNums[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Assigning value while creating the array without specifying array type.
Even shorter versions just assign values in the curly braces.
int rollNums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Using Arrays.setAll (Lambda)
First, create an int array of size 10, then using setAll to set the value of the corresponding indices. setAll takes IntUranaryOperator as the second argument. IntUranaryOperator is a functional interface and we can use lambda expressions to implement it.
int rollNums[] = new int[10];
Arrays.setAll(rollNums, p -> p + 1);
Using Arrays.setAll (Anonymous Class)
Same as above but rather than lambda expression implementing it as Anonymous class and implementing applyAsInt method.
int rollNums[] = new int[10];
Arrays.setAll(rollNums, new IntUnaryOperator () {
      @Override
      public int applyAsInt(int operand) {
        return operand + 1;
 }} );
Arrays.copyOf
We can also copy contents of an existing array to a different array of the same type.
int rollNums2[] = Arrays.copyOf(rollNums, rollNums.length);
Summary
  • We can create an array in java using a new operator and specify size while creating.
  • We can also specify the content of the array and java will create an array of sufficient size.
  • When we create an array and does not initialize then the content of the array is null if the type of the array is of type object
  • and 0 if the type is int.

No comments :

Post a Comment

Please leave your message queries or suggetions.