Types of Arrays

In Java, an array is a collection of elements of the same type stored in a single variable. It helps in organizing and managing data efficiently. There are different types of arrays in Java, each with its own purpose.

  • Single-Dimensional Array: A single-dimensional array is the most basic type of array in Java. It stores elements in a linear form (like a list).

Here, numbers is an array that holds five integer values.

Use case: Storing multiple values of the same type, like student marks or product prices.

  • Multi-Dimensional Array: A multi-dimensional array is an array of arrays. The most common type is the 2D array, which can be thought of as a table with rows and columns.

This represents a 3×3 matrix (3 rows and 3 columns).

Use case: Storing grid-like data, such as a chessboard, a tic-tac-toe game, or tables.

  • Jagged Array: A jagged array is a multi-dimensional array where each row can have a different number of columns.

Here, the first row has 3 elements, the second row has 2 elements, and the third row has 4 elements.

Use case: When rows have different numbers of elements, such as storing test scores for students who took different numbers of exams.

  • Array of Objects: Instead of storing primitive values like int or double, an array can hold objects.

Use case: Storing multiple objects, like a list of students, employees, or products.

  • Anonymous Arrays: An anonymous array is created without explicitly declaring its type and size.

Here, we pass an anonymous array {10, 20, 30} directly to the displayArray method.

Use case: When you need a temporary array for one-time use.