Arrays in Java – DSA Notes
1. Introduction
- An Array is a collection of elements of the same data type, stored in contiguous memory locations.
- Each element is accessed using an index (0-based in Java).
Example:
int arr[] = {10, 20, 30, 40};
[Link](arr[2]); // 30
2. Array Declaration & Initialization
Declaration:
int[] arr; int arr[];
Memory Allocation:
arr = new int[5];
Initialization:
int[] arr = {1, 2, 3, 4, 5};
3. Default Values
- Numeric types → 0
- boolean → false
- char → '\u0000'
- Objects → null
4. Array Length
int[] arr = new int[10];
[Link]([Link]);
5. Traversing Arrays
For loop:
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
Enhanced for loop:
for (int x : arr) {
[Link](x + " ");
}
6. Multidimensional Arrays
Declaration:
int[][] matrix = new int[3][3];
Initialization:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Traversal:
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
7. Jagged Arrays
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];
8. Important Operations
1. Searching
- Linear Search O(n)
- Binary Search O(log n)
2. Sorting: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort.
3. Reversal
int n = [Link];
for (int i = 0; i < n/2; i++) {
int temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
9. Advantages of Arrays
- Easy random access using index
- Contiguous memory allocation → cache friendly
- Simple to use
10. Disadvantages of Arrays
- Fixed size
- Insertion/Deletion costly (O(n))
- Only stores elements of same type
Alternative: ArrayList
11. Time Complexity (Big-O)
Access (arr[i]) -> O(1)
Search (Linear) -> O(n)
Search (Binary, sorted) -> O(log n)
Insert/Delete (at end) -> O(1)