Top 5 Java Array Coding Interview Questions and Solutions (Core Java + Java 8) - Part 2
π Introduction :
Arrays are one of the most fundamental data structures in Java and are frequently used to test a candidate's problem-solving ability during technical interviews. Whether you're applying for a Java Developer, Spring Boot Developer, or Java Full Stack Developer role, array-based coding questions are almost guaranteed to appear in coding rounds and technical discussions.
In this article, we'll solve five of the most frequently asked Java Array coding interview questions using both Core Java and Java 8 Streams (where applicable). Each solution includes a clear explanation of the logic, interview notes, and optimized approaches to help you understand not just how the code works, but why it works.
Instead of memorizing the answers, try solving each problem yourself before reviewing the solution. Consistent practice will strengthen your problem-solving skills and boost your confidence during coding interviews.
π Top 5 Problems
✅ Interview Question 1
Find the Largest Element in an Array
✅ Interview Question 2
Find the Second Largest Element in an Array
✅ Interview Question 3
Move All Zeros to the End of an Array
✅ Interview Question 4
Find Duplicate Elements in an Array
✅ Interview Question 5
Check Whether Two Arrays are Equal
Let's begin!
Interview Question 1: Find the Largest Element in an Array
π’ Difficulty: Easy
❓ Interview Question
How do you find the largest element in an array in Java?
π Problem Statement
Write a Java program to find the largest element in a given integer array.
π₯ Example
Example 1
Input
[10, 25, 8, 45, 32]
Output
Largest Element : 45
Example 2
Input
[-5, -10, -2, -8]
Output
Largest Element : -2
π» Solution 1 – Core Java
public class LargestElement { public static void main(String[] args) { int[] numbers = {10, 25, 8, 45, 32}; int largest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > largest) { largest = numbers[i]; } } System.out.println("Largest Element : " + largest); } }
Output
Largest Element : 45
π Solution 2 – Java 8 Streams
import java.util.Arrays; public class LargestElementStream { public static void main(String[] args) { int[] numbers = {10, 25, 8, 45, 32}; int largest = Arrays.stream(numbers) .max() .getAsInt(); System.out.println("Largest Element : " + largest); } }
Output
Largest Element : 45
π Explanation
Finding the largest element in an array is one of the most fundamental array operations and is frequently asked in Java interviews. The idea is to compare each element in the array with the current largest value.
In the Core Java approach, we initialize the first element of the array as the largest value. We then iterate through the remaining elements using a for loop. Whenever we find an element greater than the current largest value, we update the largest variable. After the loop completes, the largest variable contains the maximum value in the array.
In the Java 8 Stream approach, we convert the array into an IntStream using Arrays.stream(). The max() method returns the maximum value as an OptionalInt, and getAsInt() retrieves the actual integer value.
Both approaches are efficient and suitable for interview scenarios. While the loop-based solution demonstrates a strong understanding of array traversal, the Stream solution showcases familiarity with Java 8's functional programming features.
π Interview Note
-
Time Complexity:
O(n)because each element is visited exactly once. -
Space Complexity:
O(1)for the Core Java approach since no extra data structure is used. The Stream approach also processes the array efficiently with constant additional space. - In interviews, explain the loop-based solution first, then mention the Java 8 Stream approach as an alternative if the interviewer asks for a modern implementation.
π‘ Interview Tip
A common follow-up question is:
"How would you find the second largest element without sorting the array?"
Being prepared for this naturally leads into the next interview question and demonstrates a deeper understanding of array manipulation.
Interview Question 2: Find the Second Largest Element in an Array
π‘ Difficulty: Easy to Medium
❓ Interview Question
How do you find the second largest element in an array without sorting it?
π Problem Statement
Write a Java program to find the second largest element in an integer array without sorting the array.
Note: Assume the array contains at least two distinct elements.
π₯ Example
Example 1
Input
[12, 35, 1, 10, 34, 1]
Output
Second Largest Element : 34
Example 2
Input
[100, 25, 89, 76, 99]
Output
Second Largest Element : 99
π» Solution 1 – Core Java
public class SecondLargestElement { public static void main(String[] args) { int[] numbers = {12, 35, 1, 10, 34, 1}; int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for (int number : numbers) { if (number > largest) { secondLargest = largest; largest = number; } else if (number > secondLargest && number != largest) { secondLargest = number; } } System.out.println("Largest Element : " + largest); System.out.println("Second Largest Element : " + secondLargest); } }
Output
Largest Element : 35 Second Largest Element : 34
π Solution 2 – Java 8 Streams
import java.util.Arrays; public class SecondLargestElementStream { public static void main(String[] args) { int[] numbers = {12, 35, 1, 10, 34, 1}; int secondLargest = Arrays.stream(numbers) .distinct() .boxed() .sorted((a, b) -> b - a) .skip(1) .findFirst() .orElseThrow(); System.out.println("Second Largest Element : " + secondLargest); } }
Output
Second Largest Element : 34
π Explanation
Finding the second largest element is a common Java interview question because it tests your ability to solve problems efficiently without relying on sorting.
In the Core Java approach, we maintain two variables: largest and secondLargest. Initially, both are assigned Integer.MIN_VALUE. As we iterate through the array, we compare each element with the current largest value.
-
If the current element is greater than
largest, we updatesecondLargestwith the previouslargestvalue and assign the new value tolargest. -
If the current element is smaller than
largestbut greater thansecondLargest, we updatesecondLargest.
This approach finds both values in a single traversal of the array, making it highly efficient.
In the Java 8 Stream approach, we first remove duplicate values using distinct(). We then convert primitive integers into wrapper objects with boxed(), sort the elements in descending order, skip the first (largest) element, and retrieve the next value as the second largest element.
Although the Stream solution is concise and expressive, the Core Java approach is generally preferred in interviews because it avoids sorting and demonstrates better algorithmic thinking.
π Interview Note
- Core Java: Time Complexity – O(n), Space Complexity – O(1)
- Java 8 Streams: Time Complexity – O(n log n) due to sorting, Space Complexity – O(n)
Interview Tip: Always explain the loop-based solution first. If the interviewer asks for an alternative or modern approach, then present the Java 8 Stream solution.
π‘ Common Mistake
Many beginners sort the array first and then return the second last element.
Arrays.sort(numbers); System.out.println(numbers[numbers.length - 2]);
This approach may produce incorrect results when duplicate values are present.
Example:
Input: [10, 20, 20, 30] Sorted: [10, 20, 20, 30] Second Last = 20 ✅ But what if: [30, 30, 20] Sorted: [20, 30, 30] Second Last = 30 ❌ Expected = 20
To handle such cases correctly, either remove duplicates before sorting or use the single-pass approach shown above.
Interview Question 3: Move All Zeros to the End of an Array
π‘ Difficulty: Medium
❓ Interview Question
How do you move all zeros to the end of an array while maintaining the order of non-zero elements?
π Problem Statement
Write a Java program to move all the 0s in an integer array to the end while preserving the relative order of the non-zero elements.
Note: The operation should rearrange the array without changing the order of non-zero elements.
π₯ Example
Example 1
Input
[0, 1, 0, 3, 12]
Output
[1, 3, 12, 0, 0]
Example 2
Input
[4, 0, 5, 0, 0, 8, 2]
Output
[4, 5, 8, 2, 0, 0, 0]
π» Solution 1 – Core Java
import java.util.Arrays; public class MoveZerosToEnd { public static void main(String[] args) { int[] numbers = {0, 1, 0, 3, 12}; int index = 0; // Move all non-zero elements to the front for (int i = 0; i < numbers.length; i++) { if (numbers[i] != 0) { numbers[index++] = numbers[i]; } } // Fill the remaining positions with zeros while (index < numbers.length) { numbers[index++] = 0; } System.out.println(Arrays.toString(numbers)); } }
Output
[1, 3, 12, 0, 0]
π Solution 2 – Java 8 Streams
import java.util.Arrays; import java.util.stream.IntStream; public class MoveZerosToEndStream { public static void main(String[] args) { int[] numbers = {0, 1, 0, 3, 12}; int[] result = IntStream.concat( Arrays.stream(numbers).filter(num -> num != 0), Arrays.stream(numbers).filter(num -> num == 0) ).toArray(); System.out.println(Arrays.toString(result)); } }
Output
[1, 3, 12, 0, 0]
π Explanation
This problem is commonly asked in Java coding interviews because it tests your understanding of array traversal, in-place modification, and efficient problem-solving.
In the Core Java approach, we use an index variable to keep track of the position where the next non-zero element should be placed. We iterate through the array once and copy all non-zero elements to the beginning of the array. After processing all elements, the remaining positions are filled with zeros.
This approach preserves the original order of non-zero elements and avoids using an additional array, making it both efficient and interview-friendly.
In the Java 8 Stream approach, we create two separate streams: one containing all non-zero elements and another containing all zero elements. These streams are then combined using IntStream.concat(), producing a new array where all non-zero values appear first, followed by all zeros.
While the Stream solution is concise and expressive, the Core Java solution is generally preferred in interviews because it performs the operation in-place without allocating another array.
π Interview Note
- Core Java: Time Complexity – O(n), Space Complexity – O(1)
- Java 8 Streams: Time Complexity – O(n), Space Complexity – O(n) (creates a new array)
Interview Tip: If the interviewer asks for an optimized solution, mention that the Core Java approach modifies the existing array in-place, which is more memory efficient.
π‘ Common Mistake
Many beginners swap zeros immediately when they encounter them, which can change the order of non-zero elements.
For example:
Input: [0, 5, 0, 2, 8] Correct Output: [5, 2, 8, 0, 0]
Always ensure that the relative order of non-zero elements remains unchanged, as this is usually part of the interview requirement.
Interview Question 4: Find Duplicate Elements in an Array
π‘ Difficulty: Medium
❓ Interview Question
How do you find duplicate elements in an integer array in Java?
π Problem Statement
Write a Java program to identify and print all duplicate elements present in an integer array.
Note: Display each duplicate element only once, even if it appears multiple times.
π₯ Example
Example 1
Input
[4, 2, 7, 4, 8, 2, 9]
Output
Duplicate Elements : [4, 2]
Example 2
Input
[10, 20, 30, 40]
Output
No Duplicate Elements Found
π» Solution 1 – Core Java
import java.util.HashSet; import java.util.Set; public class FindDuplicateElements { public static void main(String[] args) { int[] numbers = {4, 2, 7, 4, 8, 2, 9}; Set<Integer> uniqueElements = new HashSet<>(); Set<Integer> duplicateElements = new HashSet<>(); for (int number : numbers) { if (!uniqueElements.add(number)) { duplicateElements.add(number); } } if (duplicateElements.isEmpty()) { System.out.println("No Duplicate Elements Found"); } else { System.out.println("Duplicate Elements : " + duplicateElements); } } }
Output
Duplicate Elements : [2, 4]
Note: Since
HashSetdoes not maintain insertion order, the output order may vary.
π Solution 2 – Java 8 Streams
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class FindDuplicateElementsStream { public static void main(String[] args) { int[] numbers = {4, 2, 7, 4, 8, 2, 9}; Set<Integer> unique = new HashSet<>(); Set<Integer> duplicates = Arrays.stream(numbers) .boxed() .filter(number -> !unique.add(number)) .collect(Collectors.toSet()); if (duplicates.isEmpty()) { System.out.println("No Duplicate Elements Found"); } else { System.out.println("Duplicate Elements : " + duplicates); } } }
Output
Duplicate Elements : [2, 4]
π Explanation
Finding duplicate elements is a common coding interview problem that evaluates your understanding of arrays, collections, and efficient searching techniques.
In the Core Java approach, we use two HashSet objects:
- uniqueElements stores all unique values encountered while traversing the array.
- duplicateElements stores only the elements that appear more than once.
When we attempt to add an element to uniqueElements, the add() method returns:
-
trueif the element is added successfully (first occurrence). -
falseif the element already exists in the set.
Whenever add() returns false, we add that element to the duplicateElements set.
In the Java 8 Stream approach, we first convert the array into a stream using Arrays.stream(). The boxed() method converts primitive int values into Integer objects. We then use a HashSet to track unique elements, and the filter() operation selects only duplicate values, which are collected into a set.
Both approaches are efficient and eliminate duplicate results automatically.
π Interview Note
- Core Java: Time Complexity – O(n), Space Complexity – O(n)
- Java 8 Streams: Time Complexity – O(n), Space Complexity – O(n)
Interview Tip: Explain why
HashSetis preferred over nested loops. It reduces the time complexity from O(n²) to O(n), making the solution much more efficient.
π‘ Common Mistake
Many beginners solve this problem using two nested loops.
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(numbers[i]); } } }
Although this works, it has a time complexity of O(n²) and may print the same duplicate multiple times.
Using a HashSet is a cleaner and more efficient solution.
Interview Question 5: Check Whether Two Arrays are Equal
π‘ Difficulty: Medium
❓ Interview Question
How do you check whether two arrays are equal in Java?
π Problem Statement
Write a Java program to check whether two integer arrays are equal. Two arrays are considered equal if they have the same length and contain the same elements in the same order.
π₯ Example
Example 1
Input
Array 1 : [10, 20, 30, 40] Array 2 : [10, 20, 30, 40]
Output
Arrays are Equal
Example 2
Input
Array 1 : [10, 20, 30] Array 2 : [30, 20, 10]
Output
Arrays are Not Equal
Note: Even though both arrays contain the same elements, the order is different. Therefore, they are not considered equal.
π» Solution 1 – Core Java
import java.util.Arrays; public class ArrayEquality { public static void main(String[] args) { int[] array1 = {10, 20, 30, 40}; int[] array2 = {10, 20, 30, 40}; if (Arrays.equals(array1, array2)) { System.out.println("Arrays are Equal"); } else { System.out.println("Arrays are Not Equal"); } } }
Output
Arrays are Equal
π Solution 2 – Java 8 Streams
import java.util.stream.IntStream; public class ArrayEqualityStream { public static void main(String[] args) { int[] array1 = {10, 20, 30, 40}; int[] array2 = {10, 20, 30, 40}; boolean isEqual = array1.length == array2.length && IntStream.range(0, array1.length) .allMatch(i -> array1[i] == array2[i]); System.out.println(isEqual ? "Arrays are Equal" : "Arrays are Not Equal"); } }
Output
Arrays are Equal
π Explanation
Checking whether two arrays are equal is a frequently asked interview question because it evaluates your understanding of array comparison and built-in utility methods.
In the Core Java approach, we use the Arrays.equals() method provided by the Java Collections Framework. This method first checks whether both arrays have the same length. If they do, it compares each corresponding element one by one. If every element matches in the same position, the method returns true; otherwise, it returns false.
In the Java 8 Stream approach, we first verify that both arrays have the same length. We then use IntStream.range() to iterate through all valid indices and compare the corresponding elements using the allMatch() method. If every comparison returns true, the arrays are considered equal.
Both approaches are simple, efficient, and suitable for interview scenarios. However, using Arrays.equals() is generally preferred because it is concise, readable, and optimized.
π Interview Note
- Core Java: Time Complexity – O(n), Space Complexity – O(1)
- Java 8 Streams: Time Complexity – O(n), Space Complexity – O(1)
Interview Tip: Mention that
Arrays.equals()compares both the length and the order of elements. If the interviewer asks you to compare arrays regardless of order, you should sort both arrays first or use a frequency map.
π‘ Common Mistake
Many beginners compare arrays using the == operator.
int[] array1 = {10, 20, 30}; int[] array2 = {10, 20, 30}; System.out.println(array1 == array2);
Output
false
The == operator compares object references, not the contents of the arrays.
The correct approach is:
Arrays.equals(array1, array2);
This compares the actual elements of both arrays.
π Conclusion :
In this article, we explored five of the most frequently asked Java Array coding interview questions that are commonly asked in Java Developer, Spring Boot Developer, and Java Full Stack Developer interviews. We solved each problem using both Core Java and Java 8 Streams (where applicable), along with detailed explanations, interview tips, and optimized approaches.
The problems covered essential array concepts such as finding the largest and second largest elements, moving zeros to the end, identifying duplicate elements, and comparing two arrays. These questions help strengthen your understanding of array traversal, searching, manipulation, and efficient problem-solving techniques.
Practice these programs regularly and try writing the solutions without referring to the code. Building strong coding fundamentals will improve your confidence and performance in technical interviews.
In Part 3, we'll explore Top 5 Java Collections Coding Interview Questions and Solutions (Core Java + Java 8), covering commonly asked interview problems using List, Set, Map, and the Java Collections Framework.
πͺ Practice Challenge
Try solving these problems on your own before checking the solutions:
- Find the smallest element in an array.
- Reverse an array without using another array.
- Find the missing number in an array.
- Rotate an array to the left by one position.
- Find the frequency of each element in an array.
π‘ Challenge Yourself: Try implementing each problem using both Core Java and Java 8 Streams wherever applicable.
π Continue Learning
If you're preparing for Java coding interviews, don't miss the previous article in this series:
πΉ Part 1: Top 5 Java String Coding Interview Questions and Solutions (Core Java + Java 8)
https://sulochanabasavala.blogspot.com/2026/07/java-string-coding-interview-questions-part-1.htmlMaster String-based coding questions before moving on to Arrays, as String problems are among the most frequently asked in Java interviews.
Happy Coding! π

Comments
Post a Comment