Array Operations in Java: Traverse, Sum, Max, Search, Reverse and More

Difficulty: Beginner · Importance: High · Java version: All versions (tested on JDK 25) · Last updated: 3 Nov 2026

Quick puzzle: temperatures in Leh are {-4, -9, -2, -7}. Your max-finding loop starts with int max = 0;. What does it print? 0, a temperature that never happened. This lesson shows the right way to do this and every other basic array operation.

Quick Answer

Array operations in Java are the everyday tasks you perform on an array with a loop: traversing, summing, finding the max and min, counting, searching, reversing, swapping, filling and building running totals. Almost all of them visit each element once, so they run in O(n) time. Most need only a few extra variables, so they use O(1) extra space.

Before you start: read Introduction to Arrays and For Loop in Java.

How to Iterate an Array in Java

There are two loops for walking through an array:

LoopSyntaxUse it when
Counted for loopfor (int i = 0; i < arr.length; i++)You need the index: to change elements, go in reverse, skip steps or compare neighbours
Enhanced for-each loopfor (int mark : marks)You only read each value

Three rules to remember:

  • Always use i < arr.length. <= reads one slot past the end and throws ArrayIndexOutOfBoundsException.
  • arr.length is a field. Reading it every pass is constant-time, so there’s no need to store it in another variable.
  • The for-each variable is a copy. Assigning to it never changes the array (see Mistake 1).

Sum, Average, Max, Min and Count in One Pass

One loop can produce a whole report card:

Output:

Total:   382Average: 63.666666666666664
Highest: 91, Lowest: 38
Passed: 5 of 6

▶ Try it in the ExamAdda Compiler

What to notice:

  • Accumulators are declared before the loop. total and passed start at 0 outside the loop. Declared inside it, they would reset on every pass (Mistake 4).
  • Max and min are seeded with marks[0], not 0. A seed of 0 breaks for all-negative data, as in the puzzle. With a counted loop you can start at i = 1, because index 0 is already used as the seed.
  • Counting is a sum that adds 1 only when a condition is true.
  • Use a double for the average. The (double) cast avoids integer division.
  • Check for an empty array first. With {}, marks[0] throws ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0, so check marks.length > 0 before seeding.

Small detail: total += mark is shorthand for total = total + mark, but += also includes a hidden cast. That’s why byte b = 1; b += 2; compiles, while b = b + 2; doesn’t.

Linear Search and Reverse an Array in Java

Output:

121 found at index 2Reversed: [142, 135, 121, 117, 104]

▶ Try it in the ExamAdda Compiler

Linear Search

Linear search checks elements one by one until it finds a match.

  • -1 is the “not found” value, because no real index can be negative.
  • break stops at the first match. You’ll find more on this in Break and Continue.
  • It takes O(n) time. If you search the same data many times, sort it once and use binary search instead, which you’ll learn in the DSA track.
  • For a String[], compare with .equals(), not == (Mistake 5).

How Reversing an Array Works

Whiteboard
Loading diagram...

Two indexes start at opposite ends and swap, then each moves one step inward. The loop stops when they meet or cross, so each element is touched once.

Dry run on {104, 117, 121, 135, 142}:

Stepleftrightleft < right?Array after the swap
104true[142, 117, 121, 135, 104]
213true[142, 135, 121, 117, 104]
322falseStop: the middle element stays in place

Complexity: O(n) time and O(1) extra space. This two-pointer pattern appears in many DSA problems.

How to Swap Two Elements in an Array

Swapping always needs a third variable, temp: save the first value, overwrite the first slot with the second value, then put the saved value in the second slot. Tricks like XOR or arithmetic swaps also work, but they are harder to read and can overflow, so avoid them.

Fill an Array and Build a Running Total (Prefix Sum)

Output:

Attendance: [-1, -1, -1, -1]Running total: [1200, 2000, 3500, 4100]
Days 2-4: 2900

▶ Try it in the ExamAdda Compiler

  • Fill only when the default isn’t what you want. new int[4] is already all zeros. Fill when you need a different starting value, such as -1 for “not marked”. Arrays.fill does this in one call, replacing a manual loop.
  • A running total (prefix sum) stores, at each index, the sum of everything up to that index. Building it takes O(n). After that, the sum of any range is one subtraction, which is O(1).

Array Operations and Their Time Complexity

OperationTimeExtra spaceLoop to use
Traverse / printO(n)O(1)for-each
Sum, average, countO(n)O(1)for-each
Max / minO(n)O(1)for-each, or a counted loop from i = 1
Linear searchO(n) worst caseO(1)Counted loop (you need the index) + break
Reverse in placeO(n)O(1)Two indexes
Swap two elementsO(1)O(1)—
FillO(n)O(1)Arrays.fill
Build a prefix sumO(n)O(n)Counted loop from i = 1

Common Mistakes

Each output below comes from a real run on JDK 25.

Mistake 1: Changing Elements Through a for-each Loop

 [100, 200, 300]

Why it happens: fee is a copy of each element. Fix: for (int i = 0; i < fees.length; i++) fees[i] *= 2;

Mistake 2: Swapping Without temp

 [33, 22, 33]

Why it happens: the first line destroyed the value 11. Fix: save it in temp first.

Mistake 3: Seeding Max With 0

wrong max = 0right max = -2

Fix: int max = temps[0];.

Mistake 4: Declaring the Accumulator Inside the Loop

total = 1200total = 800
total = 1500

Fix: declare int total = 0; before the loop.

Mistake 5: Searching Strings With ==

 == false, equals true

Why it happens: == checks whether two references point to the same object, not whether the text matches. Fix: cities[1].equals(typed). You’ll learn why in the Strings section.

Mistake 6: Using <= or Starting at the Wrong Index

i <= arr.length throws ArrayIndexOutOfBoundsException. Starting at i = 1 by accident silently skips the first element. Start at i = 1 only when index 0 was already used, as a seed or a prefix-sum base.

Best Practices

  1. Use for-each to read and a counted loop to write or when you need the index.
  2. Seed max/min from the array, and handle empty arrays first.
  3. Declare accumulators before the loop.
  4. Return -1 for “not found”, and use break once you’ve found the match.
  5. Use Arrays.toString, Arrays.fill and Arrays.copyOf instead of writing your own loops for these.
  6. Swap with temp, and keep the code readable.

Interview Questions on Array Operations

How to answer in an interview: “How do you reverse an array in place?”
“I use two indexes, one at the start and one at the end. While left is less than right, I swap the two elements using a temp variable, then move left forward and right back. It visits each element once, so it’s O(n) time, and it needs only a few variables, so it’s O(1) extra space.”

Output-Prediction Questions

Q1.

Answer: 5. Assigning to the for-each variable doesn’t change the array.

Q2.

Answer: 0. The bad seed is never beaten, because all the values are positive.

Q3. What does linear search return for a value that isn’t in the array, if foundAt starts at -1?
Answer: -1.

Conceptual Follow-Ups

  1. Why is linear search O(n)? In the worst case it checks every element.
  2. When would you use binary search instead? When the array is sorted and you search it many times.
  3. What’s the space complexity of in-place reversal? O(1).
  4. Why start the max loop at index 1? Index 0 is already the seed.
  5. What is a prefix sum used for? Answering range-sum queries in O(1) after O(n) setup.

More: Java Interview Questions for Freshers · Scenario-Based Questions

Practice Exercises

  1. Easy: Print an array of prices in reverse order without changing it.
  2. Easy: Count how many even numbers an array contains.
  3. Easy–Medium: Find the second-highest mark in one pass.
  4. Medium: Return the index of the last occurrence of a value, or -1 if it isn’t there.
  5. Medium: Using a prefix sum, answer “total sales from day l to day r” for three different ranges.

Practise on ExamAdda Practice and the ExamAdda DSA track.

FAQs

1. How do you find the maximum value in an array in Java?
Seed a variable with arr[0], then loop through the array and update it whenever an element is larger. Don’t seed it with 0, which fails for all-negative arrays.

2. How do you find the sum of array elements in Java?
Declare int total = 0; before a loop, then add each element with total += value. Divide by arr.length as a double to get the average.

3. How do you reverse an array in Java without another array?
Use two indexes from both ends and swap the elements with a temp variable until the indexes meet. This takes O(n) time and O(1) extra space.

4. Can a for-each loop modify an array in Java?
No. The loop variable is a copy, so assigning to it doesn’t change the array. Use a counted for loop with arr[i] = … instead.

5. What is the time complexity of linear search?
O(n) in the worst case, because it may check every element. It returns the index of the first match, or -1 if there isn’t one.

Quiz

1. Which loop should you use to double every element of an array?
a) for-each b) Counted for c) Either d) Neither
Answer: b. for-each can’t write back to the array.

2. What is the best seed for finding the minimum?
a) 0 b) Integer.MAX_VALUE or arr[0] c) -1 d) arr.length
Answer: b. arr[0] is the simplest; Integer.MAX_VALUE also works.

3. What is the extra space used by in-place reversal?
a) O(n) b) O(1) c) O(log n) d) O(n²)
Answer: b.

4. Given runningTotal = [1200, 2000, 3500, 4100], what is the sum of index 1 to index 2?
a) 2300 b) 3500 c) 2000 d) 1500
Answer: a. 3500 − 1200 = 2300.

Article Summary

  • Use a counted loop when you need the index or want to write to the array, and for-each for read-only work.
  • Declare accumulators before the loop, and seed max/min from the array itself.
  • Linear search returns the first index or -1, and uses break to stop early.
  • Reverse in place with two indexes and a temp swap, in O(n) time and O(1) space.
  • Arrays.fill sets a starting value, and a prefix sum turns range sums into one subtraction.

Next → [INTERNAL LINK: next Array lesson] · ← Previous: Introduction to Arrays

References: java.util.Arrays Javadoc (JDK 25) · JLS §14.14.2: The enhanced for statement · JLS §15.26.2: Compound assignment operators