Arrays in Java
A Complete Guide with Examples and Theory
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 Type | Default Value |
int | 0 |
double | 0.0 |
boolean | false |
char | '\u0000' (null character) |
String/Objects | null |
π 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
arritself 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 throwArrayIndexOutOfBoundsException.
π 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
forloop if you need access to the index.Use a
for-eachloop 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
| Operation | Complexity |
| Access (Read/Write) | O(1) |
| Search (Linear) | O(n) |
| Search (Binary - Sorted Array) | O(log n) |
| Insert at End | O(1) |
| Insert at Beginning | O(n) |
| Insert at Middle | O(n) |
| Deletion at End | O(1) |
| Deletion at Beginning | O(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! π




