Working with Arrays

Arrays are used to store multiple values in a single variable. This tutorial will cover declaring, initializing, and manipulating arrays.

Declaring and Initializing Arrays

To declare an array, define the variable type with square brackets:


int[] numbers = new int[5]; // Declaration and instantiation
int[] numbers = {1, 2, 3, 4, 5}; // Declaration and initialization
      

Accessing and Modifying Array Elements

You can access an array element by referring to the index number:


int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Outputs 1
numbers[0] = 10; // Modifies the first element
      

Multidimensional Arrays

To create a multidimensional array, add each array within its own set of square brackets:


int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
System.out.println(matrix[0][0]); // Outputs 1
      

Continue exploring our beginner tutorials to learn more about Java programming.

Scroll to Top