Array of Values

Learn and practice manipulating arrays of values in Java.

What is an array?

In Java, an array is a collection of the same type of values stored as a single variable. For example, {10, 20, 30} is an array of integers. It can be stored as a variable as shown in the code below:

The following program demonstrates how to create an array of integer values:

Press + to interact
class Test
{
public static void main(String args[])
{
int[] arr = {10, 20, 30};
System.out.println("The array is defined");
}
}

In the code above:

  • We declare a variable arr to assign {10, 20, 30}. These comma-separated values enclosed in curly brackets are called an initialization array.
  • We call the variable arr an array, as indicated by [], before the variable name. These brackets are used to explicitly mention that the variable is an array. Here, the size 3 is determined by the number of values in the initialization array.

Accessing individual values

The individual values in an array are accessed through an index. An index is an integer representing the position of an individual value in the array. We enclose the index in square brackets after the array variable name. The first value is at the index 0, and the index moves forward in the array by linear increments. If there are three values in the array, they are indexed at 0,1, ...