Table of contents
- 1️⃣ What is an Array?
- 2️⃣ Declaring & Initializing Arrays in Java
- 3️⃣ Accessing & Modifying Elements
- 4️⃣ Iterating Over an Array
- 5️⃣ Important Array Operations
- 6️⃣ Types of Arrays
- 7️⃣ Common Array Problems
- 8️⃣ Time Complexity of Array Operations
- 9️⃣ Best Resources for Arrays
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
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 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
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
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! 🚀