BCA / B.Tech 9 min read

Arrays in Java

What is an Array in Java?

An array is a container object that holds a fixed number of values of a single type. It provides an ordered collection of elements, where each element is accessed via a numerical index. Think of it as a row of numbered mailboxes, where each mailbox can hold one item of the same kind.

Key Features:
  • Fixed Size: The length of an array is established when it's created and cannot be changed.
  • Homogeneous: All elements in an array must be of the same data type (e.g., an array of integers or an array of strings).
  • Indexed: Elements are accessed using a zero-based index. The first element is at index 0, the second at index 1, and so on.

Declaring and Initializing Arrays:

// 1. Declaration: Specifies the type of the array.
int[] scores;

// 2. Instantiation: Creates the array object in memory with a specific size.
scores = new int[5]; // This array can hold 5 integers.

// 3. Initialization: Assigning values to the elements.
scores[0] = 95;
scores[1] = 87;
// ...and so on.
        

You can also declare, instantiate, and initialize an array in a single line:

String[] names = {"Alice", "Bob", "Charlie"};

Types of Arrays:
  • Single-Dimensional Array: A simple, linear list of elements.
    int[] numbers = {10, 20, 30, 40};
  • Multi-Dimensional Array: An array of arrays, often used to represent grids or matrices.
    int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    // Access element at row 1, column 2 (value is 6)
    int element = matrix[1][2];
                    

Accessing an element with an index that is out of bounds (e.g., `scores[5]` in the first example) will result in an ArrayIndexOutOfBoundsException.