• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

Initialize an Array in Java | Simple to Advanced

March 8, 2024 //  by Shameen Shahid

In Java, arrays are the fundamental data structures that store a fixed number of multiple values at contiguous memory locations. In the array, the stored values are known as elements. These elements can be accessed by specifying the index within the array. An array is initialized in Java when values are given to it. Several ways for initializing an array in Java are discussed and implemented in this article. 

Initialize the Array Using the Simplest Approach 

In Java, you can initialize an array using the default values, the “new” keyword, or through the user input. One of the most common practices is to initialize the array when declared. Given below are the various methods for initializing an array.

Method 1: Initialize the Array With Default Values 

An array “numArray” is declared with the desired length. The for loop iterates through the elements of the array and prints the value at the current index “numArray[i]” using the println() method. The loop terminates when the array’s length is reached. In Java, the value at each index is “0” which is the default value as shown in the output given below:

package initializeArray;
public class initalizeArray {
public static void main(String[] args)
{
    //Initializing with default values
    int[ ] numArray = new int[2];

    //printing the array
    for (int i=0;i<numArray.length;i++)
    {
System.out.println("numArray" + "[" + i + "]  = " + numArray[i] );
    }
}
}

Output

Method 2: Initialize the Array With Defined Values 

In Java, the length of the array is also automatically determined by the compiler when initializing it. In the following code, the “numArrayValues” is initialized using the  “new” keyword which is followed by the elements within the curly braces. The for loop go through the elements of the array and prints them with a single space between them. The special character “\n” is used to add a line separator after the loop terminated to increase readability:

//Assigning Dynamic Values
int[ ] numArrayValues = new int[ ] {1,2,3,4};
System.out.println("Printing the Integer array ");
for(int i =0; i<numArrayValues.length; i++){
    System.out.print(numArrayValues[i]  + "  ");
}
System.out.println("\n");

Similarly, another method of initializing the array is by assigning values to it while declaring it as shown in the code below. The elements of the string array “strArray” are then printed on the console:

//Initializing the Array while declaring
String[ ]  strArray = {"Welcome","to","JavaBeat"} ;
System.out.println("Printing the String array ");
for(int i =0; i<strArray.length; i++)
{
  System.out.print(strArray[i]  + "  ");
}
System.out.println("\n");

A slightly different approach to initializing the array is by specifying the square braces with the array’s name. The elements are defined in the curly braces and the for loop prints each index’s value using the print statement:

//Creating a Float Array
float floatArray [ ]  = { 1.0f , 2.99f, 3.8f, 4.5f};
System.out.println("Printing the float Array ");
for(int i =0; i<floatArray.length; i++)
{
  System.out.print(floatArray[i]  + "  ");
}
System.out.println("\n");

In this code, the “indexArray” with the length “3” is initialized by specifying the index “indexArray[1]”. The first and second indexes will be storing the following values. The for loop prints the array elements:  

//Initializing the Array at Specific Index
int [ ] indexArray=new  int[3];
indexArray[1]= 2;
indexArray[2] = 5;
System.out.println("Printing the Array initialized by specifying indexes ");
for(int i =0; i<indexArray.length; i++)
{
    System.out.print(indexArray[i]  + "  ");
}

Output 

Method 3: Initialize the Array With User Input 

Arrays can be initialized via the user input. For this, the Scanner class is imported from the “java.util” package using the following import statement. The Scanner class provides methods for taking the user input and manipulating it accordingly:

import java.util.Scanner;

Inside the main() method, the string array with the length “2” is declared. The Scanner class object “input” is created using the “new” keyword that accepts the standard input i.e., input via the keyboard:

String [ ] strArray = new String[2];//creating an array with default values
Scanner input = new Scanner (System.in);

The for loop iterates over the array elements and prompts the user to enter the value for the given index. The user input is read by using the next() method which is invoked by the Scanner object “input”: 

for(int i=0;i<strArray.length;i++)
{
System.out.println("Enter value at " + "\"" + i  + "\"" + " of Array ?");
strArray[ i ] = input.next();
}

After the user input is stored in the array, another for loop is used to print the value at each index of the array as shown in the code below:

for(int i=0;i<strArray.length;i++)
{
  System.out.println("The value at" + "\"" + i  + "\"" + " index is " + strArray[i]);
}

Output

Initialize the Array Using the Built-in Methods

In Java, there are different built-in and static methods provided by the Java classes and API such as Arrays and Stream. 

Method 1: Initialize the Array Using the Arrays Class 

The following import statement brings in the Arrays class from the “java.util” package:

import java.util.Arrays;

The integer array “numArray” is declared with the size “10”. The Arrays class invokes the static fill() method that accepts two arguments i.e., integer array “numArray” and the value that is to be added to the array. The fill() method will add the value “90” at each index of the array.

//Initializing the Array using the Fill() method
int [ ] numArray = new int[ 3];
Arrays.fill(numArray, 90);
System.out.println("Initializing the Array using the fill() Method");
for (int i =0 ; i<numArray.length; i++)
{
    System.out.print(numArray[i] + "  ");
}
System.out.println("\n");

Similarly, another method provided by the Arrays class is the setAll() method. For this, an array “strArray” is declared. The setAll() method is a static method that accepts strArray and a generator function as parameters. The generator function (i -> “Hello”) will place the “Hello” word at each index of the “strArray”. Each element of the array is then traversed and printed as shown below: 

// Initializing the Array using the setAll() Method
String [ ] strArray = new String[ 3];

Arrays.setAll(strArray, i -> "Helllo");

//Printing the Array
System.out.println("Initializing the Array using the setAll() method ");
for (int i =0 ; i<strArray.length; i++)
{
  System.out.print(strArray[i] + "  ");}
System.out.println("\n");

Complete Code & Output

Method 2: Initialize an Array Using Stream

The stream is a subpackage of the “java.util” package. It provides various static methods, classes, and interfaces for working with data in the stream format.

In the following import statement, the “IntStream” class is imported from the “java.util.stream” package:

import java.util.stream.IntStream;

The IntStream class invokes the range() method that accepts the two integer values. The “0” and “9” specified that the first element will be 0 and the next elements will be greater than 0 but less than 9. The toArray() method converts the stream into an array which is then stored in the “numArray”. The values of the array are then printed using the for loop and println() method:

//Initializing the Array using the range() method
int [ ] numArray = IntStream.range(0 ,  9).toArray();
System.out.println("Initializing the Array using the range() method");
for (int i : numArray)
{
  System.out.print(numArray[i] + "   ");
}
System.out.println("\n");

Similarly, another method of the IntStream class is the rangeClosed() method. The rangeClosed() method also accepts two parameters. The “0” indicates that the first element is 0 and the next elements will be greater than 0 and less than or equal to “3”. The difference between range() and rangeClosed() is that the array will contain the last element i.e., 3. The output is then printed on the console: 

//Initializing the Array using the rangeClosed()
int [ ] arr1 = IntStream.rangeClosed(0, 3).toArray();
System.out.println("Initializing the Array using the rangeClosed() Method");
for (int i =0; i< arr1.length; i++)
{
  System.out.print(arr1[i] + " ");
}System.out.println("\n");

The IntStream class offers of() method that initializes the array similar to the assigning values within the curly braces. In the following code, the IntStream.of() method accepts different values that will be stored in the form of an array returned by the toArray() method. The “arr2” elements are then printed using the for loop and println() method with a single space between them for readability:

//Initializing the Array using the IntStream.of()
int [ ] arr2 = IntStream.of(1,2,3,4,5,10).toArray();
System.out.println("Initializing the Array Using the IntStream.of()");
for (int i =0; i< arr2.length; i++)
{
  System.out.print(arr2[i] + "  ");
}

Output

Initialize the Array Using ArrayUtils Class 

The ArrayUtils class provides several methods for manipulating arrays using the third-part library “Apache Common Lang”. To use this class, we are first required to add the “Apache Commons” dependency in the pom.xml or build.gradle file of the project:

<dependencies>
<dependency>
  <groupId>org.apache.commons</groupId>  <artifactId>commons-lang3</artifactId>
  <version>3.14.0</version>
</dependency>
</dependencies>

The dependency has been successfully added to the project:

The import statement is used to include the ArrayUtils class from the “org.apache.commons.lang3” package. Within the main() method, the “strArray” is initialized with the following elements. The ArrayUtils class invokes the static clone() method that accepts “strArray1” as an argument. All the elements of the “strArray1” will be replicated to the “strArray2”. The for loop is used to display the elements of the second array i.e., strArray2: 

package initArrayApache;
import org.apache.commons.lang3.ArrayUtils;
public class initArrayApache {
public static void main(String[] args) // code inside the main() method
{

    String[ ] strArray1= {"Welcome", "To", "JavaBeat"};
    String [ ] strArray2= ArrayUtils.clone(strArray1);
   
    //Printing each elements of the Second array
    System.out.println("The elements of Second Array are ");
    for ( int i =0 ; i< strArray2.length; i++)
    {
    System.out.println(i +"-"+ " \"" + strArray2[i] + "\"  " );
    }
}
}

Output 

How to Initialize a Multidimensional Array in Java? 

The Multi-dimensional arrays store the data in the form of rows and columns i.e., tabular format. The elements are accessed by providing the rows and columns. 

Initialize a 2-dimensional Array in Java  

In this code, the “twoDimensionalArray” is declared with 3 rows and 4 columns. The “5” value is assigned to the 3rd column of the 2nd row. The “0” value will be assigned to the remaining rows and columns:

int[ ][ ] twoDimensionalArray = new int [ 3 ][4]; //3 rows and 4 columns
 
twoDimensionalArray[2][3]= 5; //specifying at a specific index

You can also initialize the array with an equal number of rows and columns or uneven rows and columns (jagged arrays). Similarly, the “new” keyword followed by the elements that are to be stored in the “numArray” is also another way of initializing a multidimensional array in Java: 

int [ ] [ ] num_2DArray = {{1,2,3} , {3,4,5}};//defining values while declaring
int [ ] [ ] jaggedArray = {{1,2}, {3,4,5,6}}; //initializing the jagged array
 
int [ ][ ] numArray= new int[ ][ ] {{1,2,3}, {4,5,6}};//using new keyword

The first for loop iterates over each row. The second “for loop” accesses each element at the present row and column. The print statement then prints the elements of the array:

//for printing the array
for (int i=0;i<twoDimensionalArray.length;i++)
{
  for(int j=0 ; j<twoDimensionalArray.length+1 ; j++)
  {
System.out.println("Value at " + "\"" + "twoDimensionalArray" + "[" + i + "]" + "[" + j + "] " + twoDimensionalArray[i][j] + "\"" );
    }
}

Complete Code 

Output

Initialize a 3D-Array in Java 

The 3D array in Java stores multiple two-dimensional arrays with an increased dimension. In this section, the initialization of a 3D array is achieved by using the “new” keyword as shown in the code below. The value “10” is assigned at the “numArray[1] [0] [1]”. The default value “0” at each index is then printed using three for loops:

package initializeArrayJava;
public class initializearrayinJava {
public static void main(String[] args)
{
  int [ ] [ ][ ] numArray= new int[3][4][5];

  numArray[1][0][1]=10;

  for (int i =0 ;i <3; i++)
  {
  for ( int j=0;j<3; j++)
  {
  for (int k=0 ; k<3; k++)
  {
  System.out.println("numArray" + "[" + i + "]" + "[" + j + "]" + "[" + k + "] =  " + numArray[i][j][k] + "\"" );
  }
  }
  }
}
}

Output 

This sums up all the methods and approaches of initializing an array in Java.

Conclusion

Arrays are the data structure that stores various elements that share the same data type within the memory. To initialize an array in Java, use the default value, “new” keyword, or call the built-in methods such as IntStream.range(), clone(), or setAll() methods, etc. The simplest and the most efficient approach used by the developers is to initialize the arrays while declaring the array. On the other hand, you can also initialize the array with the user input by using the Scanner class methods. This article provides different simple, intermediate, and advanced methods to initialize the Array in Java.  

Category: Java

Previous Post: « How to Get String Length in Java?
Next Post: How to Find the Square Root of a Number in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact