Java Arrays: Definition, Declaration and Basic Operations

Arrays are a fundamental data structure in Java, enabling the storage and manipulation of a fixed-size collection of elements of the same type. This article explores the core concepts of array definition and declaration in Java, providing a solid foundation for working with this essential structure.

What is an Array?

An array is an object that stores a contiguous block of memory allocated for a specific number of elements of a single data type. Each element in the array is accessed using a numeric index, starting from zero. In Java, arrays are reference types, meaning the array variable holds a reference to the array object residing in the heap memory.

int[] valores = {10, 20, 30, 40, 50}; // Declares and initializes an integer array

Array Declaration Syntax

Java supports two primary syntax styles for declaring an array. The preferred and more readable style places the square brackets after the element type.

tipoDado[] nomeArray;   // Recommended style
tipoDado nomeArray[];   // Alternative style

Declaring and Initializing One-Dimensional Arrays

After declaration, an array must be initialized to allocate memory. Initialization can be done dynamically using the new keyword or statically by providing initial values.

Dynamic Initialization

This method allocates a new array of a specified size. The elements are set to their default values (e.g., 0 for integers, null for objects).

double[] leituras = new double[10]; // Creates an array of 10 doubles

Static Initialization

This shorthand syntax declares, allocates, and populates the array in a single step.

String[] nomes = {"Ana", "Bruno", "Carlos"};

Declaring and Initializing Multi-Dimensional Arrays

Multi-dimensional arrays, such as two-dimensional arrays, can represent matrix-like structures. They are arrays of arrays.

int[][] grade = new int[4][5]; // Dynamic initialization of a 4x5 matrix

Static initialization for a two-dimensional array provides the values for each inner array.

int[][] grade = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Rows in a two-dimensional array can have different lengths, creating what is known as a ragged array.

Common Pitfalls

  • ArrayIndexOutOfBoundsException: Occurs when attempting to access an index that is less than zero or greater than or equal to the array's length. Always validate index bounds.
  • NullPointerException: Thrown when invoking a method or accessing a property (like .length) on an array variable that has not been initialized (is null).
int[] dados = {5, 10, 15};
// System.out.println(dados[3]); // Throws ArrayIndexOutOfBoundsException

int[] itens = null;
// System.out.println(itens.length); // Throws NullPointerException

Example Program

The following program demonstrates the declaration, initialization, and traversal of both one-dimensional and two-dimensional arrays.

public class ExemploArrays {
    public static void main(String[] args) {
        // One-dimensional array
        int[] idades = {25, 30, 45, 18, 52};
        for (int idx = 0; idx < idades.length; idx++) {
            System.out.println("Idade no índice " + idx + ": " + idades[idx]);
        }

        // Two-dimensional array
        int[][] planilha = {
            {10, 20, 30},
            {40, 50, 60}
        };
        for (int linha = 0; linha < planilha.length; linha++) {
            for (int coluna = 0; coluna < planilha[linha].length; coluna++) {
                System.out.print(planilha[linha][coluna] + "\t");
            }
            System.out.println();
        }
    }
}

Characteristics and Usage

Arrays offer constant-time O(1) access to elements via their index, making them highly efficient for retrieval. How ever, their fixed size is a significant limitation, as resizing an array requires creating a new array and copying elements. For dynamic collections, classes like ArrayList are often preferred. Multi-dimensional arrays are particularly useful for applications involving matrices, grids, or tabular data.

Tags: java Arrays Data Structures Programming Fundamentals Multi-dimensional Arrays

Publicado em 6-5 19:00 por Thomas