Skip to main content

Command Palette

Search for a command to run...

Arrays in Java

A Complete Guide with Examples and Theory

Updated
β€’8 min read

Arrays are one of the most fundamental data structures in programming. They provide a way to store multiple values of the same type in a contiguous block of memory, making data access efficient.

In this blog, we’ll take a deep dive into Java Arrays, covering everything from basic concepts to advanced operations, common problems, and their solutions with code examples.


1️⃣ What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations. Each element in an array is accessed using an index, starting from 0.

πŸ“Œ Key Features of Arrays:

βœ” Fixed Size: The size of an array is defined at the time of declaration and cannot be changed later.
βœ” Indexing: Elements are accessed using their position (0-based index).
βœ” Efficient Access: Accessing any element takes O(1) time, making arrays fast for lookups.
βœ” Homogeneous Elements: All elements must be of the same data type.

πŸ“Œ Why Use Arrays?

Arrays provide a convenient way to store multiple related values, such as:

  • Storing student scores in an exam.

  • Keeping track of stock prices over a week.

  • Storing a collection of user IDs.


2️⃣ Declaring & Initializing Arrays in Java

πŸ“Œ Declaration of Arrays

In Java, an array must be declared before it can be used. The declaration tells the compiler that a variable will hold an array reference, but it does not allocate memory for the elements yet.

int[] arr;  // Preferred syntax
int arr2[]; // Also valid but less common

πŸ”Ή The preferred syntax is int[] arr; because it clearly indicates that arr is an array of integers.

πŸ’‘ Key Takeaway:

  • Declaring an array does not allocate memory for the elements; it just creates a reference variable.

πŸ“Œ Initialization of Arrays

After declaration, memory must be allocated for the array elements using the new keyword.

int[] arr = new int[5];  // Allocates memory for 5 integers (default values are 0)

πŸ”Ή The above statement creates an array of size 5 and initializes all elements with the default integer value (0).

πŸ’‘ Default Values of Array Elements

If you don’t explicitly initialize an array, Java assigns default values based on the data type:

Data TypeDefault Value
int0
double0.0
booleanfalse
char'\u0000' (null character)
String/Objectsnull

πŸ“Œ Declaring and Initializing Together

Java also allows declaring and initializing an array at the same time:

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

πŸ”Ή This is useful when the array size and values are known in advance.

πŸ”Έ Memory Allocation Insight:

  • Java stores arrays in heap memory, which means they are dynamically allocated at runtime.

  • The variable arr itself is stored in stack memory, holding a reference to the heap location.


3️⃣ Accessing & Modifying Elements

πŸ“Œ Accessing Array Elements

Array elements are accessed using their index, which starts from 0 in Java.

System.out.println(arr[2]); // Access element at index 2 (returns 30)

πŸ”Ή Attempting to access an index beyond the array size will cause an ArrayIndexOutOfBoundsException.

⚠️ Important: Accessing an invalid index (arr[10] if array size is 5) will throw ArrayIndexOutOfBoundsException.

πŸ“Œ Modifying Array Elements

You can modify an array element by assigning a new value:

arr[1] = 25; // Changes value at index 1 from 20 to 25

πŸ’‘ Key Notes:

  • Array elements are mutable, meaning their values can be changed after initialization.

  • However, the size of the array cannot be changed once allocated.


4️⃣ Iterating Over an Array

πŸ“Œ Using a For Loop

A for loop is commonly used to iterate through an array:

for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
}

πŸ”Ή This approach gives full control over indexing, making it useful when modifying values during iteration.

πŸ“Œ Using an Enhanced For-Each Loop

The for-each loop is a simpler way to iterate when modifications are not required:

for (int num : arr) {
    System.out.print(num + " ");
}

πŸ”Ή The for-each loop is more readable but does not allow modifying array elements directly.

πŸ’‘ Best Practice:

  • Use a for loop if you need access to the index.

  • Use a for-each loop for read-only operations.


5️⃣ Important Array Operations

Arrays are used in various operations like finding length, copying, sorting, and reversing. These operations are crucial in real-world applications and competitive programming. Let’s go through them one by one.

πŸ“Œ 1. Finding the Length of an Array

Java provides the .length property to get the number of elements in an array.

System.out.println("Array Length: " + arr.length);

πŸ”Ή This operation runs in O(1) time complexity since the array length is stored as a property and can be accessed instantly.

πŸ“Œ 2. Copying an Array

Sometimes, we need to copy an array to another variable. Java provides multiple ways to achieve this:

πŸ‘‰ Using Arrays.copyOf()

int[] copy = Arrays.copyOf(arr, arr.length);

πŸ”Ή This creates a new array and copies all elements from the original array.

πŸ‘‰ Using System.arraycopy() (More Efficient)

int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);

πŸ”Ή System.arraycopy() is more efficient as it copies memory blocks directly instead of iterating over elements.

πŸ“Œ 3. Sorting an Array

Sorting is a common operation used in searching, ranking, and optimization problems.

πŸ‘‰ Using Arrays.sort()

Arrays.sort(arr); // Sorts the array in ascending order

πŸ”Ή Arrays.sort() uses Dual-Pivot QuickSort (O(n log n)) for primitive types and TimSort (Hybrid MergeSort) for objects.

πŸ‘‰ Sorting in Descending Order

Integer[] arrObj = {10, 5, 3, 8};
Arrays.sort(arrObj, Collections.reverseOrder());

πŸ”Ή Note that Collections.reverseOrder() works only with Integer[], not int[].

πŸ“Œ 4. Reversing an Array

Reversing an array is useful in many scenarios like string processing and mathematical problems.

πŸ‘‰ Using a Loop (Efficient Method)

for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

πŸ”Ή This swaps elements from both ends until the middle is reached.

πŸ‘‰ Using Collections.reverse() (For Integer Objects)

Collections.reverse(Arrays.asList(arrObj));

πŸ”Ή This method works for Integer[] but not for primitive int[].


6️⃣ Types of Arrays

Arrays in Java come in different types, including 1D Arrays, 2D Arrays, and Jagged Arrays.

πŸ“Œ 1D Array (Single Dimensional)

A one-dimensional array is the simplest form of an array, where elements are stored in a linear structure.

int[] arr = {1, 2, 3, 4, 5};

πŸ”Ή This is equivalent to a list or vector in other programming languages.

πŸ“Œ 2D Array (Multi-Dimensional)

A two-dimensional array is like a table (matrix) with rows and columns.

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

πŸ”Ή The first bracket matrix[i] represents the row, while matrix[i][j] represents the column.

πŸ‘‰ Accessing a 2D Array

System.out.println(matrix[1][2]); // Output: 6

πŸ”Ή This accesses the second row, third column of the matrix.

πŸ“Œ Jagged Arrays (Variable Column Size)

Jagged arrays have varying column sizes, unlike normal 2D arrays.

int[][] jagged = new int[3][];
jagged[0] = new int[2];  // Row 0 has 2 columns
jagged[1] = new int[3];  // Row 1 has 3 columns
jagged[2] = new int[1];  // Row 2 has 1 column

πŸ”Ή These are useful when rows don’t need to have the same number of elements.


7️⃣ Common Array Problems

πŸ“Œ 1. Find Maximum & Minimum Element

int max = arr[0], min = arr[0];
for (int i = 1; i < arr.length; i++) {
    if (arr[i] > max) max = arr[i];
    if (arr[i] < min) min = arr[i];
}
System.out.println("Max: " + max + ", Min: " + min);

πŸ”Ή The above method has a time complexity of O(n).

πŸ“Œ 2. Check If Array is Sorted

boolean isSorted = true;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] < arr[i - 1]) {
        isSorted = false;
        break;
    }
}
System.out.println("Sorted: " + isSorted);

πŸ”Ή This method scans the entire array to check for order in O(n) time complexity.

πŸ“Œ 3. Remove Duplicates from a Sorted Array

int index = 1;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] != arr[i - 1]) {
        arr[index++] = arr[i];
    }
}
System.out.println("New length: " + index);

πŸ”Ή This method runs in O(n) time and modifies the array in place.

πŸ“Œ 4. Move Zeroes to End

int index = 0;
for (int num : arr) {
    if (num != 0) arr[index++] = num;
}
while (index < arr.length) arr[index++] = 0;

πŸ”Ή Moves all zeroes to the end while keeping the order of non-zero elements.


8️⃣ Time Complexity of Array Operations

OperationComplexity
Access (Read/Write)O(1)
Search (Linear)O(n)
Search (Binary - Sorted Array)O(log n)
Insert at EndO(1)
Insert at BeginningO(n)
Insert at MiddleO(n)
Deletion at EndO(1)
Deletion at BeginningO(n)
Sorting (QuickSort/MergeSort)O(n log n)

πŸ”Ή Why O(n) for inserting/deleting at the beginning?
Because elements have to shift to maintain the contiguous memory structure.


9️⃣ Best Resources for Arrays

βœ… Practice Problems: LeetCode Arrays
βœ… Theory & Basics: GeeksForGeeks Arrays
βœ… Video Explanation: Striver’s DSA Playlist

Mastering arrays is essential for DSA and coding interviews. Keep practicing, and happy coding! πŸš€