Javatpoint Logo
Javatpoint Logo

Java Initialize array

Java initialize array is basically a term used for initializing an array in Java. We know that an array is a collection of similar types of data. The array is a very important data structure used for solving programming problems.

The word element is used for the values stored in different positions of the array. In order to use the Array data structure in our code, we first declare it, and after that, we initialize it.

Declaration of an Array

The syntax of declaring an array in Java is given below.

Here, the datatype is the type of element that will be stored in the array, square bracket[] is for the size of the array, and arrayName is the name of the array.

Initializing an Array

Only the declaration of the array is not sufficient. In order to store values in the array, it is required to initialize it after declaration. The syntax of initializing an array is given below.

In Java, there is more than one way of initializing an array which is as follows:

1. Without assigning values

In this way, we pass the size to the square braces[], and the default value of each element present in the array is 0. Let's take an example and understand how we initialize an array without assigning values.

ArrayExample1.java

Output:

Java Initialize array

2. After the declaration of the array

In this way, we initialize the array after the declaration of it. We use the new keyword assigning an array to a declared variable. Let's take an example and understand how we initialize an array after declaration.

ArrayExample2.java

Output:

Java Initialize array

3. Initialize and assign values together

In this way, we declare and initialize the array together. We don't do both the declaration and initialization separately. Let's take an example and understand how we do both the thing together:

ArrayExample3.java

Output:

Java Initialize array

All the above three ways are used based on the requirement of the functionality.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA