Arrays are rarely used only for storing values. In real programs, you frequently need to search, update, insert, delete, reverse, calculate, and rearrange array elements. Java provides several ways to perform these common operations, from simple loops to methods in the Arrays utility class.
Accessing an Array Element
The most basic array operation is accessing an element using its index. Java arrays use zero-based indexing, so the first element is at index 0.
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
The first statement accesses 10, while the second accesses 30.
Updating an Element
An existing array element can be changed simply by assigning a new value to its index.
int[] numbers = {10, 20, 30, 40};
numbers[1] = 200;
System.out.println(Arrays.toString(numbers));
The value at index 1 changes from 20 to 200. Updating an element does not change the size of the array.
Finding the Length
Use the length property to determine how many elements an array can contain.
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length);
The result is 4. Notice that length is a property, not a method, so you write numbers.length rather than numbers.length().
Remember: Arrays have a fixed length after creation. You can change their elements, but you cannot increase or decrease the array's size.
Traversing an Array
Traversal means visiting each element of an array. A traditional for loop is useful when you need the index.
int[] numbers = {10, 20, 30, 40}; for (int i = 0; i < numbers.length; i++) { System.out.println("Index " + i + ": " + numbers[i]); }
When only the values matter, an enhanced for loop is often cleaner.
for (int number : numbers) { System.out.println(number); }
Finding the Sum
A common operation is calculating the total of all elements.
int[] numbers = {10, 20, 30, 40}; int sum = 0; for (int number : numbers) { sum += number; } System.out.println("Sum = " + sum);
The variable sum acts as an accumulator. Each element is added to the running total.
Finding the Average
Once you know the sum, calculating the average is straightforward. Be careful to use floating-point division when a decimal result is expected.
int[] marks = {80, 75, 90, 85}; int sum = 0; for (int mark : marks) { sum += mark; } double average = (double) sum / marks.length; System.out.println("Average = " + average);
Casting sum to double prevents integer division from discarding the fractional part.
Finding the Maximum Element
To find the largest value, keep track of the largest element seen so far.
int[] numbers = {45, 12, 78, 34, 90}; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Maximum = " + max);
Starting with the first actual element is safer than choosing an arbitrary value such as 0 because the array could contain only negative numbers.
Finding the Minimum Element
Finding the smallest value uses the same pattern, but the comparison is reversed.
int[] numbers = {45, 12, 78, 34, 90}; int min = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < min) { min = numbers[i]; } } System.out.println("Minimum = " + min);
Searching for an Element
A linear search checks elements one by one until the required value is found.
int[] numbers = {15, 25, 35, 45, 55}; int target = 35; int index = -1; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == target) { index = i; break; } } System.out.println("Index = " + index);
The value -1 is commonly used to indicate that the target was not found.
Counting Occurrences
Sometimes you need to know how many times a particular value appears.
int[] numbers = {10, 20, 10, 30, 10, 40}; int target = 10; int count = 0; for (int number : numbers) { if (number == target) { count++; } } System.out.println("Occurrences = " + count);
The counter increases each time the target value is encountered.
Reversing an Array
A common programming exercise is reversing an array in place. The idea is to exchange the first element with the last, the second with the second-last, and continue toward the center.
int[] numbers = {10, 20, 30, 40, 50}; int left = 0; int right = numbers.length - 1; while (left < right) { int temp = numbers[left]; numbers[left] = numbers[right]; numbers[right] = temp; left++; right--; } System.out.println(Arrays.toString(numbers));
The two-pointer technique avoids creating another array and is a useful pattern that appears frequently in interview problems.
Sorting an Array
Sorting arranges elements into a defined order. For ascending order, the Arrays.sort() method is usually the simplest choice.
int[] numbers = {50, 10, 40, 20, 30};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
The resulting array is arranged from the smallest value to the largest value.
Checking Whether an Array Contains a Value
For a simple unsorted array, you can use a loop to check whether a value exists.
int[] numbers = {10, 20, 30, 40}; int target = 30; boolean found = false; for (int number : numbers) { if (number == target) { found = true; break; } } System.out.println("Found = " + found);
For sorted arrays, binary search can be used when its performance characteristics are appropriate.
Copying an Array
To create an independent copy, use a copying method rather than assigning the original reference.
int[] original = {10, 20, 30}; int[] copy = Arrays.copyOf(original, original.length); copy[0] = 100; System.out.println(Arrays.toString(original)); System.out.println(Arrays.toString(copy));
The original array remains unchanged because copy refers to a separate array object.
Comparing Arrays
To compare the contents of two one-dimensional arrays, use Arrays.equals().
int[] first = {10, 20, 30}; int[] second = {10, 20, 30}; boolean same = Arrays.equals(first, second); System.out.println(same);
This compares the values rather than simply checking whether both variables refer to the same array.
Inserting an Element
Java arrays have a fixed size, so you cannot directly insert an element and increase the existing array's length. A new larger array must be created.
int[] original = {10, 20, 40, 50}; int[] result = new int[original.length + 1]; int position = 2; System.arraycopy(original, 0, result, 0, position); result[position] = 30; System.arraycopy(original, position, result, position + 1, original.length - position); System.out.println(Arrays.toString(result));
The new array contains 30 at index 2, while the original elements after that position are shifted one place to the right.
Deleting an Element
Deleting an element also requires a new array because an array cannot shrink after creation.
int[] original = {10, 20, 30, 40}; int[] result = new int[original.length - 1]; int position = 1; System.arraycopy(original, 0, result, 0, position); System.arraycopy(original, position + 1, result, position, original.length - position - 1); System.out.println(Arrays.toString(result));
The element at index 1 is skipped, so the resulting array contains 10, 30, and 40.
Important: If your application frequently inserts or removes elements, an array may not be the most suitable data structure. Java collections such as ArrayList are often more convenient for dynamic-sized data.
Finding Duplicate Values
A simple way to detect duplicate values is to compare each element with the elements that follow it.
int[] numbers = {10, 20, 30, 20, 40}; for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] == numbers[j]) { System.out.println("Duplicate = " + numbers[i]); } } }
This approach is easy to understand, although it can become expensive for large arrays because it uses nested loops. In performance-sensitive applications, other data structures may provide a more efficient solution.
Removing Duplicates
Removing duplicates from a plain array is more involved because arrays have fixed sizes. A common approach is to use another structure or first determine which values should remain and then create a correctly sized result array.
For modern Java applications, a collection such as Set is often a better fit when the primary requirement is uniqueness rather than fixed-size indexed storage.
Checking for an Empty Array
An array is empty when its length is zero.
int[] numbers = new int[0]; if (numbers.length == 0) { System.out.println("Array is empty"); }
An empty array is different from a null array reference. A null reference does not refer to an array object at all.
Handling Null Arrays
Before accessing length or an element, make sure the array reference is not null when null is a possible state.
int[] numbers = null; if (numbers != null) { System.out.println(numbers.length); } else { System.out.println("Array reference is null"); }
Trying to access numbers.length when numbers is null causes a NullPointerException.
Common Array Operations at a Glance
| Operation | Typical Approach | Key Point |
|---|---|---|
| Access | array[index] | Uses zero-based indexing |
| Update | array[index] = value | Changes an existing element |
| Traversal | for or for-each | Visits elements |
| Search | Loop or binarySearch() | Binary search requires suitable ordering |
| Sort | Arrays.sort() | Changes the original array |
| Copy | Arrays.copyOf() | Creates a separate array |
| Compare | Arrays.equals() | Compares one-dimensional contents |
| Reverse | Two-pointer technique | Can be performed in place |
| Insert | Create larger array | Original array size cannot grow |
| Delete | Create smaller array | Original array size cannot shrink |
| Min/Max | Loop | Track the best value seen so far |
| Sum/Average | Accumulator loop | Average may require floating-point division |
Common Beginner Mistakes
- Using an invalid index and causing an ArrayIndexOutOfBoundsException.
- Trying to change an array's size after it has been created.
- Using integer division when calculating an average that should contain decimals.
- Assuming array assignment creates an independent copy.
- Using binary search on data that is not appropriately sorted.
- Ignoring the difference between an empty array and a null array reference.
Best Practices
- Use array.length instead of hard-coded sizes when traversing arrays.
- Prefer enhanced for loops when the index is not required.
- Use the Arrays utility class for standard operations such as sorting, copying, and comparison.
- Use meaningful variable names that describe what the array stores.
- Choose a collection instead of an array when the data size changes frequently.
Interview Insight
A common interview question is: “Can you insert or delete an element directly from a Java array?” The answer is no. Java arrays have a fixed length after creation. To insert or delete an element, you normally create another array and copy the required elements. If frequent modifications are expected, a dynamic collection such as ArrayList is usually a better choice.
Common array operations become much easier once you understand the two fundamental properties of arrays: elements are accessed by index, and the array's length is fixed after creation. From searching and sorting to reversing and calculating statistics, most operations are built from simple traversal patterns or the helpful methods provided by the Arrays utility class. Master these patterns and you will have a strong foundation for solving many Java programming and interview problems.
