Java Notes
20+ complete Java array programs with solutions, detailed explanations, step-by-step logic, input/output examples covering all common array programming problems.
This section contains 20 essential array programs that cover the most commonly asked problems in interviews and exams. Each program includes complete code, explanation of the approach, and actual output.
Program 1: Find the Largest Element
Problem: Find the maximum value in an array.
Approach: Initialize max with first element, then compare with every other element.
Array: [45, 23, 89, 12, 67, 34, 78, 56] Largest element: 89
Time Complexity: O(n) | Space Complexity: O(1)
Program 2: Find Second Largest Element
Problem: Find the second largest element without sorting.
Approach: Track both first and second largest in a single pass.
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
System.out.println("Array: " + java.util.Arrays.toString(arr));
System.out.println("Largest: " + first);
System.out.println("Second Largest: " + second);
}
}Array: [12, 35, 1, 10, 34, 1] Largest: 35 Second Largest: 34
Time Complexity: O(n) | Space Complexity: O(1)
Program 3: Sum and Average of Array Elements
public class SumAverage {
public static void main(String[] args) {
int[] marks = {85, 92, 78, 90, 88, 76, 95};
int sum = 0;
for (int mark : marks) {
sum += mark;
}
double average = (double) sum / marks.length;
System.out.println("Marks: " + java.util.Arrays.toString(marks));
System.out.println("Sum: " + sum);
System.out.printf("Average: %.2f%n", average);
}
}Marks: [85, 92, 78, 90, 88, 76, 95] Sum: 604 Average: 86.29
Program 4: Reverse an Array In-Place
Original: [1, 2, 3, 4, 5, 6, 7] Reversed: [7, 6, 5, 4, 3, 2, 1]
Program 5: Count Frequency of Each Element
Array: [2, 3, 2, 4, 5, 3, 2, 4, 5, 5, 5] Element | Frequency --------|---------- 2 | 3 3 | 2 4 | 2 5 | 4
Program 6: Remove Duplicates from Sorted Array
Original: [1, 1, 2, 2, 3, 3, 3, 4, 5, 5] After removing duplicates: [1, 2, 3, 4, 5] Unique count: 5
Program 7: Move All Zeros to End
Problem: Move all zeros to the end while maintaining order of non-zero elements.
Original: [0, 1, 0, 3, 12, 0, 5, 0, 8] After moving zeros: [1, 3, 12, 5, 8, 0, 0, 0, 0]
Program 8: Find Missing Number (1 to N)
Problem: Given an array of n-1 integers in range 1 to n, find the missing number.
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6, 7, 8}; // Missing: 3
int n = arr.length + 1; // Should have n numbers
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
int missing = expectedSum - actualSum;
System.out.println("Array: " + java.util.Arrays.toString(arr));
System.out.println("Expected sum (1 to " + n + "): " + expectedSum);
System.out.println("Actual sum: " + actualSum);
System.out.println("Missing number: " + missing);
}
}Array: [1, 2, 4, 5, 6, 7, 8] Expected sum (1 to 8): 36 Actual sum: 33 Missing number: 3
Program 9: Two Sum Problem
Problem: Find two numbers that add up to a given target.
Array: [2, 7, 11, 15, 3, 6] Target: 9 Pair found: 2 + 7 = 9 Indices: [0, 1]
Program 10: Kadane's Algorithm (Maximum Subarray Sum)
Problem: Find the contiguous subarray with the largest sum.
Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4] Maximum subarray sum: 6 Subarray: [4, -1, 2, 1]
Program 11: Check if Array is Sorted
[1, 3, 5, 7, 9, 11] is sorted: true [1, 3, 2, 7, 5] is sorted: false
Program 12: Left Rotate Array by K Positions
Original: [1, 2, 3, 4, 5, 6, 7] Left rotated by 3: [4, 5, 6, 7, 1, 2, 3]
Program 13: Find Leaders in Array
Problem: An element is a "leader" if it is greater than all elements to its right.
Array: [16, 17, 4, 3, 5, 2] Leaders: 2 5 17
Program 14: Dutch National Flag (Sort 0s, 1s, 2s)
Original: [2, 0, 1, 2, 1, 0, 0, 2, 1, 0] Sorted: [0, 0, 0, 0, 1, 1, 1, 2, 2, 2]
Program 15: Find Majority Element (appears > n/2 times)
Array: [2, 2, 1, 1, 1, 2, 2] Majority element: 2 (appears 4 times)
Program 16: Intersection of Two Arrays
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {4, 5, 6, 7, 8, 9};
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) set1.add(num);
List<Integer> intersection = new ArrayList<>();
for (int num : arr2) {
if (set1.contains(num)) {
intersection.add(num);
}
}
System.out.println("Array 1: " + Arrays.toString(arr1));
System.out.println("Array 2: " + Arrays.toString(arr2));
System.out.println("Intersection: " + intersection);
}
}Array 1: [1, 2, 3, 4, 5, 6] Array 2: [4, 5, 6, 7, 8, 9] Intersection: [4, 5, 6]
Program 17: Find Equilibrium Index
Problem: Find index where sum of left elements equals sum of right elements.
Array: [-7, 1, 5, 2, -4, 3, 0] Equilibrium index: 3 Left sum = Right sum = -1
Program 18: Find All Pairs with Given Sum
Array: [1, 5, 7, -1, 5, 3, 6, 2] Target sum: 6 Pairs: (1, 5) at indices [0, 1] (1, 5) at indices [0, 4] (7, -1) at indices [2, 3] (3, 3) at indices [5, 5]
Program 19: Merge Two Sorted Arrays
Array 1: [1, 3, 5, 7, 9] Array 2: [2, 4, 6, 8, 10] Merged: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Program 20: Check if Array is a Palindrome
[1, 2, 3, 2, 1] is palindrome: true [1, 2, 3, 4, 5] is palindrome: false
Common Mistakes
- Off-by-one errors in loop boundaries causing ArrayIndexOutOfBoundsException
- Not handling empty arrays — always check
arr.length == 0before processing - Modifying array while iterating — can lead to skipped elements
- Integer overflow — when summing large arrays, use
longinstead ofint - Forgetting edge cases — single element arrays, all same elements, all negatives
Best Practices
- Start with brute force then optimize — understand the problem first
- Draw examples on paper before coding — trace through with small inputs
- Handle edge cases first — empty array, single element, no match
- Use meaningful variable names —
maxSoFarinstead ofm - Test with multiple inputs — sorted, reverse sorted, duplicates, negatives
- Know time complexity — understand why O(n) is better than O(n²)
- Use built-in methods for production code —
Arrays.sort(),Arrays.binarySearch() - Comment your logic — especially for tricky algorithms like Kadane's
Interview Questions
Q1: What is the time complexity of finding the largest element? O(n) — must check every element at least once.
Q2: How do you find duplicates in O(n) time? Use a HashSet — add each element; if add() returns false, it's a duplicate.
Q3: What is Kadane's Algorithm? An O(n) algorithm to find the maximum sum subarray. It maintains a running sum and resets when the sum becomes negative.
Q4: How do you rotate an array in O(1) space? Use the reversal algorithm: reverse first k elements, reverse remaining, reverse all.
Q5: What is Moore's Voting Algorithm? Finds the majority element (>n/2 occurrences) in O(n) time O(1) space by tracking a candidate and its count.
Q6: What is the Dutch National Flag problem? Sort an array of 0s, 1s, and 2s in O(n) time O(1) space using three pointers (low, mid, high).
Q7: How do you find the missing number in 1..n? Use the formula: missing = n*(n+1)/2 - actualSum. Or use XOR of all elements with 1..n.
Q8: What is an equilibrium index? An index where sum of elements on the left equals sum of elements on the right.
Q9: How do you merge two sorted arrays efficiently? Use two pointers technique — compare elements from both arrays and pick the smaller one. Time: O(n+m).
Q10: What is the Two Sum problem? Find two numbers that add up to a target. Optimal: use HashMap for O(n) time O(n) space.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Array Programs — Fundamentals.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, arrays, array
Related Java Master Course Topics