Initializing Arrays in Java

Initializing Arrays in Java

In this post, we will cover different options for Initializing Arrays in Java along with main differences with each option.

 

Introduction

In this post, we will be covering some of the commonly used ways for Initializing Arrays in Java, we will also discuss briefly these different options and subtle differences between them.

 

1. Initializing using Loop

One of the simplest ways is to initialize an array using a loop, this method will fill one element at a time in the Array.

for( int i=0; i< length ; i++){
    data[i] = i;
}

 

2. Initializing During Declaration

If we know about the size and element of the array, we can also initialize it at the declaration time.

int[] data = {101,201,130,401,350,660,771,880,890,891};

int[] data;
data = new int[] {100,200,300,400,500,600,710,800,900,912};

String[] strings = new String[] {"Sunday", "Monday","Tuesday"};

Please be aware the with above syntax, you will not be able to initialize after this, the system will be throwing a compile-time error if we will try to do this.

 

3. Arrays.fill()

Arrays class contains various methods for manipulating arrays, we can use any of the Arrays.fill() method to fill given the array with the same value.

long array[] = new long[15];
Arrays.fill(array, 20);

There are multiple variations of the fill method which can be used based on the requirement.

 

4. Arrays.setAll()

These methods set all elements of the specified array, using the provided generator function to compute each element.

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

 

Summary

In this short post, we covered different options to Initializing Arrays in Java. These are handy techniques and commonly used in the day to day development.

JavaDevJournal

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz