How to initialize an Array in Java

Filed Under: Java

Today we will learn how to initialize an array in java. An array in java is a container that can hold a fixed number of values of the same type. The values can be of the primitive type like int, short, byte or it can be an object like String, Integer etc.

How to initialize an Array in Java

how to initialize an array in java, java array initialization

An array can be one dimensional or it can be multidimensional also. When we invoke length of an array, it returns the number of rows in the array or the value of the leftmost dimension.

We can initialize an array using new keyword or using shortcut syntax which creates and initialize the array at the same time.

When we create an array using new operator, we need to provide its dimensions. For multidimensional arrays, we can provide all the dimensions or only the leftmost dimension of the array.

Let’s see some valid ways to initialize an array in java.

Initializing an array in java – primitive type

//initialize primitive one dimensional array
int[] arrInt = new int[5];

Initializing an array in java – object type

//initialize Object one dimensional array
String[] strArr; //declaration

strArr = new String[4]; //initialization

Initializing a multidimensional array in java

//initialize multidimensional array
int[][] twoArrInt = new int[4][5];

//multidimensional array initialization with only leftmost dimension
int[][] twoIntArr = new int[2][];
twoIntArr[0] = new int[2];
twoIntArr[1] = new int[3]; //complete initialization is required before we use the array

How to initialize an array in java using shortcut syntax

//array initialization using shortcut syntax
int[] arrI = {1,2,3};
int[][] arrI2 = {{1,2}, {1,2,3}};

If you notice above, the two dimensional array arrI2 is not a symmetric matrix. It’s because a multidimensional array in java is actually an array of array. For complete explanation, refer Two Dimensional Array in Java.

Invalid ways to initialize an array in java

Here are some invalid ways to initialize an array.

//invalid because dimension is not provided
int[] a = new int[];

//invalid because leftmost dimension value is not provided
int[][] aa = new int[][5];

Here are some other variations of declaring arrays in java but they are strongly discouraged to avoid confusion.

int[] twoArrInt[] = new int[4][5];

int twoIntArr[][] = new int[5][];

That’s all for declaring and initializing an array in java.

Reference: Java Array Oracle page


  1. Will says:

    Thanks for posting this.

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content