Array Usage Techniques
Fundamental Array Operations
1. Accessing Array Elements
public class ArrayAccess {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Accessing by index
int firstElement = numbers[0]; // 10
int lastElement = numbers[numbers.length - 1]; // 50
}
}
Iteration Techniques
Iteration Methods
graph TD
A[Array Iteration] --> B[Standard For Loop]
A --> C[Enhanced For Loop]
A --> D[Stream API]
A --> E[Iterator]
Iteration Examples
public class ArrayIteration {
public static void main(String[] args) {
int[] scores = {85, 90, 75, 88, 92};
// Standard for loop
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
// Enhanced for loop
for (int score : scores) {
System.out.println(score);
}
// Stream API iteration
Arrays.stream(scores).forEach(System.out::println);
}
}
Array Manipulation Techniques
Common Array Operations
Operation |
Method |
Description |
Sorting |
Arrays.sort() |
Sorts array in ascending order |
Copying |
Arrays.copyOf() |
Creates a copy of array |
Filling |
Arrays.fill() |
Fills array with specific value |
Searching |
Arrays.binarySearch() |
Finds element index |
Advanced Manipulation Example
public class ArrayManipulation {
public static void main(String[] args) {
int[] original = {5, 2, 8, 1, 9};
// Sorting
Arrays.sort(original);
// Copying
int[] copied = Arrays.copyOf(original, original.length);
// Filling
int[] filledArray = new int[5];
Arrays.fill(filledArray, 42);
// Searching
int index = Arrays.binarySearch(original, 5);
}
}
Multi-Dimensional Array Techniques
Creating and Using 2D Arrays
public class MultiDimensionalArrayDemo {
public static void main(String[] args) {
// 2D array initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Nested loop iteration
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Error Handling and Best Practices
Array Boundary Checks
public class SafeArrayAccess {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
// Safe access with boundary check
try {
int value = safelyAccessArray(numbers, 5);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index");
}
}
private static int safelyAccessArray(int[] arr, int index) {
if (index >= 0 && index < arr.length) {
return arr[index];
}
throw new ArrayIndexOutOfBoundsException("Invalid index");
}
}
graph TD
A[Array Performance] --> B[Direct Index Access]
A --> C[Minimal Overhead]
A --> D[Contiguous Memory]
A --> E[Predictable Access Time]
LabEx Practical Tips
- Use appropriate iteration method
- Implement boundary checks
- Leverage built-in array methods
- Consider alternative data structures for complex scenarios
LabEx recommends mastering these techniques to become proficient in Java array manipulation.