Arrays

An array is a collection of elements of the same data type, stored in contiguous memory locations. In Java, an array allows you to store multiple values in a single variable, making it a powerful tool to manage large datasets efficiently. Each element in an array is identified by its index, which starts from 0.

Types of Arrays

Java supports different types of arrays:

Single-Dimensional Arrays: A one-row array where elements are stored in a sequential manner.

Multi-Dimensional Arrays: Arrays that contain more than one row and column, like matrices. The most common type is a 2D array.

Jagged Arrays: A special type of multi-dimensional array where each row can have different column sizes.

Declaration & Initialization

To use an array, we must declare and initialize it.

Declaration: Defines the array variable.

Initialization: Assigns values to the array.

Alternatively, we can declare and initialize the array in a single line:

Basic Operations

Here are the common operations performed on arrays:

Insertion: Adding an element at a specific index (array size must be fixed in Java).

Deletion: Removing an element (though Java arrays do not support direct deletion, we can set an index to null or shift elements manually).

Traversal: Accessing array elements using loops.

Advantages & Disadvantages

Advantages Disadvantages
Fixed size allows for efficient memory usage. Fixed size means it cannot grow dynamically.
Easy to implement and access elements using indices. Inserting/deleting elements is cumbersome.
Arrays can hold a large number of elements. Limited to one data type (e.g., only integers, strings).

Real-World Examples

  • Database Tables: Each row can be represented as an array of values.
  • Game Development: Storing the game board in a 2D array (like Tic-Tac-Toe).
  • Image Processing: Pixels of an image can be represented using arrays where each element corresponds to a color value.