Java array – How to create, declare, initialize arrays in Java with examples

What is Java array?

An array is a type of variable that can store multiple values. An array is an object in Java that contains similar data type values.

Example of declaring and accessing array

How to declare an array

This is how a Java array can be declared:

ArrayDataType[] ArrayName;

OR

ArrayDataType ArrayName[];

Where:

  • The ArrayDataType defines the data type of array element like int, double etc.
  • ArrayName is the name of that array.

You can also create/ Instantiate an array by using the new keyword as follows:

int arrayName = new int[10];

Where [10] specifies that array length is ten or array can contain ten elements.

How to assign values to arrays

This is how you can assign a value to an array:

arrayName[0] = 10;

Alternatively, you can also assign values as follows:

int[]ArrList = {1, 2, 3, 4,5};

The above array is five elements length array.

Watch Video of this Tutorial or keep reading below