Trusted answers to developer questions

How to initialize an array in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

An array is a collection of data objects of the same type. It is one of the fundamental data structures in Java and is incredibly useful for solving programming problems.

The values stored in the array are referred to as elements and each element is present at a particular index of the array.

svg viewer

Declaring an array

The syntax for declaring an array is:

datatype[] arrayName;
  • datatype: The type of Objects that will be stored in the array eg. int, char etc.

  • [ ]: Specifies that the declared variable points to an array

  • arrayName: Specifies the name of the array

Initializing an array

Declaring an array does not initialize it. In order to store values in the array, we must initialize it first, the syntax of which is as follows:

datatype [ ] arrayName = new datatype [size];

There are a few different ways to initialize an array. Look at the following examples to get a better idea about array initialization.

1. Initializing an array without assigning values:

An array can be initialized to a particular size. In this case, the default value of each element is 0.

Press + to interact
class HelloWorld {
public static void main( String args[] ) {
//Initializing array
int[] array = new int[5];
//Printing the elements of array
for (int i =0;i < 5;i++)
{
System.out.println(array[i]);
}
}
}

2. Initializing an array after a declaration:

An array can also be initialized after declaration.

Press + to interact
class HelloWorld {
public static void main( String args[] ) {
//Array Declaration
int[] array;
//Array Initialization
array = new int[]{1,2,3,4,5};
//Printing the elements of array
for (int i =0;i < 5;i++)
{
System.out.println(array[i]);
}
}
}

Note: When assigning an array to a declared variable, the new keyword must be used.

3. Initializing an array and assigning values:

An array can also be initialized during declaration.

Press + to interact
class HelloWorld {
public static void main( String args[] ) {
int[] array = {11,12,13,14,15};
//Printing the elements of array
for (int i =0;i < 5;i++)
{
System.out.println(array[i]);
}
}
}

Note: When assigning values to an array during initialization, the size is not specified.

RELATED TAGS

array
java
initialization
data structures
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?