How to initialize an array in Java

In this tutorial, we will learn how to initialize a Java Array.

What is an Array in Java?

Arrays in Java are objects that can store elements of the same data type. In a Java Array, we can store only a fixed set of elements that can be accessed using indices.

How to initialize an array in Java

Types of Arrays in Java

There are two types of Arrays in Java:

  1. Single-dimensional Array
  2. Multidimensional Array

 

Single Dimensional Array

Declaring a single-dimensional array

There are a couple of ways of declaring a single-dimensional array in java. You can do this using the following ways:

DataType[] arr;
DataType arr[];
DataType []arr;

Example:

int a[];
int[] b;
int []c;

Instantiating a single-dimensional array in Java

After declaring a single-dimensional array, to instantiate it we can use the following Syntax:

reference-variable = new DataType[size];

Example:

//one way of doing this is:
int a[];
a = new int[5];
//or it can be done in a single line
int b[] = new int[5];

 

Multidimensional Array

Declaring a Multidimensional array

Declaring of a multidimensional array can be done in the following ways:

DataType[][] reference-variable;
DataType reference-variable[][];
DataType [][]reference-variable;

Example:

int[][] a;
int b[][];
int [][]c;

Instantiating a Multidimensional array

Here is the syntax to instantiate a multidimensional array after declaring it:

reference-variable = new DataType[size][size];

Example:

//one way of doing this is:
int a[][];
a = new int[3][4];
//or it can be done in a single line
int b[][] = new int[3][4];

 

Initializing an array in Java

Single-dimensional

Here are the ways of initializing a single-dimensional array in java:

  1. We can declare, instantiate and initialize a single-dimensional array at the same time.
    int a[] = {1,2,3,4,5};
  2. We can also initialize a single-dimensional array using indices.
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;

    You can also do this using a for loop.

 

Multidimensional array

Next, you can initialize a multidimensional array in the following ways:

  1. Similar to a single-dimensional array you can initialize, instantiate and declare a multidimensional array at the same time.
    int a[2][3] = {{1,2,3},{4,5,6}};
  2. We can also initialize a multidimensional array using indices. For example,
    a[0][0] = 1;
    a[0][1] = 2;
    a[0][2] = 3;
    a[1][0] = 4;
    a[1][1] = 5;
    a[1][2] = 6;

    You can also do this using a for loop.

Leave a Reply

Your email address will not be published. Required fields are marked *