How to initialize an Array in Java With Examples

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

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

Initializing an array in java – object type

Initializing a multidimensional array in java

How to initialize an array in java using shortcut syntax

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.

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

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

Reference: Java Array Oracle page

By admin

Leave a Reply