Array Programs in Java with Solutions
Write the basic array programs in Java that practice tests and coding rounds start with.
- Time
O(n) for each program - Space
O(1), except the reverse copy, which uses O(n) - Hints3
- Read4 min
Most beginner array programs in Java follow one pattern: loop through the array once and update a variable. For the sum, add each element. For the largest, start with arr[0] and replace it when you find a bigger value. To reverse, swap the elements at the two ends and move inwards. To search, return the index when you find a match, or -1 after the loop.
Problem statement
Practise these array programs in Java. Use int[] arr = {12, 45, 7, 30, 9} and
write methods that:
- find the sum of all elements,
- find the largest element,
- find the smallest element,
- reverse the array in place, and
- search for a value and return its index, or -1.
Four more programs (average, even and odd count, second largest, reverse copy) are in
the solution section, followed by a version that reads the array with Scanner.
An integer array arr with at least one element.
The result of each program, one per line.
Examples
arr = [12, 45, 7, 30, 9]Sum 103, Largest 45, Smallest 712 + 45 + 7 + 30 + 9 = 103. 45 is the biggest value and 7 is the smallest.
arr = [12, 45, 7, 30, 9], search 30330 is at index 3. Indexes start at 0.
Constraints
- 1 <= arr.length <= 10^5
- Elements fit in an int; the sum may need a long for large arrays
Think before you code
Reveal the questions to ask yourself first
- What should the starting value of the sum be? Of the max?
- Why is starting max at 0 a bad idea?
- To reverse, which two positions swap first?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
One loop, one variable
| Program | Variable | Start value | Update in the loop |
|---|---|---|---|
| Sum | total |
0 | total += arr[i] |
| Largest | max |
arr[0] |
if arr[i] > max, max = arr[i] |
| Smallest | min |
arr[0] |
if arr[i] < min, min = arr[i] |
| Search | none | none | if arr[i] == target, return i |
| Reverse | left, right |
0, length - 1 |
swap, left++, right-- |
Each of these looks at every element at most once, so each is O(n).
If arrays are new to you, read arrays in Java first.
Dry run
Walk through the example step by step
Largest element in [12, 45, 7, 30, 9]. max starts at 12.
i | arr[i] | arr[i] > max? | max
--+--------+---------------+----
1 | 45 | yes | 45
2 | 7 | no | 45
3 | 30 | no | 45
4 | 9 | no | 45
Reverse in place:
left | right | swap | array after
-----+-------+---------+-------------------
0 | 4 | 12, 9 | [9, 45, 7, 30, 12]
1 | 3 | 45, 30 | [9, 30, 7, 45, 12]
2 | 2 | stop, left is not less than right
Solution
Reveal the full Java solution
import java.util.Arrays;
public class ArrayPrograms {
// 1. Sum of all elements
static int sum(int[] arr) {
int total = 0;
for (int x : arr) {
total += x;
}
return total;
}
// 2. Largest element
static int largest(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// 3. Smallest element
static int smallest(int[] arr) {
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
// 4. Reverse in place
static void reverse(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// 5. Linear search: index of target, or -1
static int search(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {12, 45, 7, 30, 9};
System.out.println("Array : " + Arrays.toString(arr));
System.out.println("Sum : " + sum(arr));
System.out.println("Largest : " + largest(arr));
System.out.println("Smallest : " + smallest(arr));
System.out.println("Index of 30 : " + search(arr, 30));
System.out.println("Index of 8 : " + search(arr, 8));
reverse(arr);
System.out.println("Reversed : " + Arrays.toString(arr));
}
}Output:
Array : [12, 45, 7, 30, 9]
Sum : 103
Largest : 45
Smallest : 7
Index of 30 : 3
Index of 8 : -1
Reversed : [9, 30, 7, 45, 12]
The search runs before the reverse. After reversing, 30 would be at index 1.
Java array examples: four more programs
public class MoreArrays {
public static void main(String[] args) {
int[] arr = {4, 9, 2, 9, 6, 6};
// 6. Average
int total = 0;
for (int x : arr) {
total += x;
}
double avg = (double) total / arr.length;
System.out.println("Average: " + avg);
// 7. Count even and odd
int even = 0, odd = 0;
for (int x : arr) {
if (x % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println("Even: " + even + ", Odd: " + odd);
// 8. Second largest (distinct)
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > first) {
second = first;
first = x;
} else if (x > second && x != first) {
second = x;
}
}
System.out.println("Second largest: " + second);
// 9. Copy into a new array in reverse order
int[] rev = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
rev[i] = arr[arr.length - 1 - i];
}
for (int x : rev) {
System.out.print(x + " ");
}
System.out.println();
}
}
Average: 6.0
Even: 4, Odd: 2
Second largest: 6
6 6 9 2 9 4
- Average: cast to
doublebefore dividing.total / arr.lengthwith two ints drops the decimal part. - Second largest: 9 appears twice, and the
x != firstcheck makes the answer 6, not 9.
Array practice questions with Scanner input
import java.util.Scanner;
public class ArrayInput {
// Sample input: 5 12 45 7 30 9
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int max = arr[0];
int sum = 0;
for (int x : arr) {
sum += x;
if (x > max) {
max = x;
}
}
System.out.println("Sum = " + sum);
System.out.println("Largest = " + max);
}
}
Sum = 103
Largest = 45
The first number, 5, is the size. The next five numbers are the elements.
Next array programs to try
| Program | Page |
|---|---|
| Move zeros to the end | move all zeros to the end |
| Missing number from 1 to n | find the missing number |
| Sort an array | bubble sort in Java |
| Search a sorted array fast | binary search in Java |
For string practice, go to string programs in Java.
O(n) for each programO(1), except the reverse copy, which uses O(n)Review before the interview
Common mistakes
- Starting max at 0. For [-5, -2, -9] the answer would wrongly be 0.
- Looping with i <= arr.length, which throws ArrayIndexOutOfBoundsException.
- Integer division in the average: 31 / 6 gives 5, not 5.1666.
- Writing else return -1 inside the search loop, so only index 0 is ever checked.
Edge cases to test
- Array with one element: it is both the largest and the smallest.
- Empty array: arr[0] throws an exception. Check arr.length first.
- All elements equal: there is no distinct second largest; the code above prints Integer.MIN_VALUE.
- Large values can make the sum overflow an int. Use long.
Interview follow-ups
- Can you find the largest and smallest in a single loop?
- How would you rotate an array by k positions?
- How would you find the second largest if duplicates should count?
Keep practising
Find the Largest Element in an Array
Hints · Dry run · SolutionSolve Similar problemFind the Sum of All Elements in an Array
Hints · Dry run · SolutionSolve Similar problemReverse an Array In Place
Hints · Dry run · SolutionSolve Similar problemLinear Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemFind the Second Largest Element in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun’s Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
