Java Array Operations & Common Problems - Detailed Guide

Common Array Operations

Java arrays par kai tarah ke operations perform kiye ja sakte hain jise commonly programming me use kiya jata hai:

Example: Array Traversal and Update

int[] arr = {10, 20, 30, 40, 50};
for(int i = 0; i < arr.length; i++) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}
arr[2] = 100;  // Update value at index 2
System.out.println("Updated element at index 2: " + arr[2]);

Arithmetic Operations on Arrays

Arrays par element-wise arithmetic operations bhi kar sakte hain, jaise addition, subtraction:

int[] a = {10, 20, 30};
int[] b = {1, 2, 3};
int[] sum = new int[a.length];

for(int i = 0; i < a.length; i++) {
    sum[i] = a[i] + b[i];
    System.out.println("Sum at index " + i + ": " + sum[i]);
}

Common Problems with Arrays

Example: ArrayIndexOutOfBoundsException

int[] arr = new int[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
// arr[3] = 40;  // Throws ArrayIndexOutOfBoundsException

Example: Reference Copy Issue

int[] original = {1, 2, 3};
int[] copy = original;
copy[0] = 100;
System.out.println(original[0]);  // Output: 100 (shared reference)

Best Practices to Avoid Common Problems