Top 30 Most Common Java Coding Interview Questions You Should Prepare For

Written by
James Miller, Career Coach
Introduction
Preparing for a java coding interview can feel like a daunting task, but mastering common data structures and algorithms is key to success. Interviewers use these questions to assess your problem-solving skills, understanding of fundamental concepts, and ability to write clean, efficient code in Java. This post covers thirty essential java coding interview questions, providing concise explanations and example approaches to help you build confidence. By practicing these problems, you'll gain familiarity with typical interview patterns and improve your logical thinking. Whether you're a fresh graduate or an experienced developer, reviewing these core java coding interview questions is a valuable step in your interview preparation journey. Get ready to dive into the world of effective coding solutions for your next java coding interview.
What Are Java Coding Interview Questions?
Java coding interview questions are technical challenges designed to evaluate a candidate's proficiency in the Java programming language, algorithms, and data structures. They often involve writing code on a whiteboard, in a shared editor, or directly in an IDE to solve a specific problem. These questions range from basic manipulations of strings and arrays to more complex tasks involving trees, graphs, dynamic programming, or object-oriented design principles. The goal is not always just about getting the correct answer, but also demonstrating your thought process, discussing potential optimizations, handling edge cases, and writing maintainable code. Understanding these types of java coding interview questions is fundamental for anyone seeking a software development role using Java.
Why Do Interviewers Ask Java Coding Interview Questions?
Interviewers ask java coding interview questions to gauge a candidate's core technical competencies beyond just theoretical knowledge. They want to see how you approach problems, break them down, and translate logical steps into code. Coding questions reveal your algorithmic thinking, understanding of time and space complexity, and ability to choose appropriate data structures. They also test your debugging skills and how you handle unexpected scenarios. Ultimately, performance on these java coding interview questions helps interviewers predict how effectively you will contribute to a development team, solve real-world programming challenges, and maintain code quality in a professional environment. It’s a practical way to assess your foundational programming abilities.
Preview List
Reverse a String in Java
Swap Two Numbers Without Using a Third Variable
Find the Maximum Element in an Array
Check if a Number is Prime
Find the First Duplicate in an Array
Count the Number of Vowels in a String
Check if a String is a Palindrome
Find All Permutations of a String
Find the Maximum Subarray Sum
Implement a Binary Search Algorithm
Find the First Non-Repeated Character in a String
Sort an Array Using QuickSort
Find the Middle Element of a Linked List
Merge Two Sorted Arrays
Check if a Number is a Power of Two
Find the Substring with the Maximum Length
Find All Possible Combinations of a Given Array
Check if Two Strings are Anagrams
Find the Frequency of Each Character in a String
Check if a String Contains Only Digits
Bubble Sort Algorithm
Find the Missing Number in an Array (1 to n)
Find the Kth Smallest Element in an Unsorted Array
Check if a Binary Tree is Balanced
Find the Most Frequent Element in an Array
Check if a Number is Perfect
Remove Duplicates from an Array
Find All Substrings of a String
Check if a String is a Subsequence of Another String
Find the Pair with a Given Sum in an Array
1. Reverse a String in Java
Why you might get asked this:
Tests basic string manipulation and awareness of built-in Java classes like StringBuilder
, which is efficient for modification.
How to answer:
Explain using StringBuilder
's reverse()
method or iterating through the string, appending characters to a new string or character array.
Example answer:
Use StringBuilder. Create a StringBuilder from the input string, call its reverse() method, and then convert it back to a String for output. This is the standard and most efficient approach in Java.
2. Swap Two Numbers Without Using a Third Variable
Why you might get asked this:
Evaluates basic arithmetic and bitwise logic understanding, often posed as a simple warm-up or trick question.
How to answer:
Present the arithmetic approach (a=a+b, b=a-b, a=a-b) and ideally the bitwise XOR approach (a=a^b, b=a^b, a=a^b).
Example answer:
Using XOR: Initialize two integers, say a and b. The swap uses three XOR operations: a = a ^ b; b = a ^ b; a = a ^ b;. This swaps the values without needing a temporary variable.
3. Find the Maximum Element in an Array
Why you might get asked this:
A fundamental array traversal problem that checks loop constructs and basic comparison logic.
How to answer:
Iterate through the array, keeping track of the largest element encountered so far by comparing each element with the current maximum.
Example answer:
Iterate through the array starting from the second element, assuming the first element is the initial maximum. In each step, compare the current element with the stored maximum and update if the current element is larger.
4. Check if a Number is Prime
Why you might get asked this:
Assesses understanding of loops, conditional logic, and basic number theory (optimization using square root).
How to answer:
Check for divisibility from 2 up to the square root of the number. Handle edge cases like 0, 1, and 2.
Example answer:
First, handle numbers less than or equal to 1 (not prime). Then loop from 2 up to the square root of the input number. If the number is divisible by any number in this range, it's not prime. Otherwise, it is prime.
5. Find the First Duplicate in an Array
Why you might get asked this:
Tests array traversal and the use of data structures like HashSet
for efficient lookup to detect duplicates.
How to answer:
Iterate through the array. Use a HashSet
to store elements encountered. If an element is already in the set when adding, it's the first duplicate.
Example answer:
Initialize an empty HashSet. Loop through the array elements. For each element, try to add it to the set. If the add method returns false, it means the element was already present, and you return this element as the first duplicate.
6. Count the Number of Vowels in a String
Why you might get asked this:
A simple string iteration problem checking basic loop control and character comparison skills.
How to answer:
Iterate through the string character by character. Convert the string to lowercase for case-insensitivity and check if each character is one of the vowels (a, e, i, o, u).
Example answer:
Convert the input string to lowercase. Initialize a counter to zero. Iterate through each character of the string. If the character is 'a', 'e', 'i', 'o', or 'u', increment the counter. Return the final count.
7. Check if a String is a Palindrome
Why you might get asked this:
Checks string manipulation and comparison skills, often solvable by comparing the string to its reverse or using two pointers.
How to answer:
Option 1: Reverse the string and compare it with the original. Option 2: Use two pointers, one from the start and one from the end, moving inwards and comparing characters.
Example answer:
Create a StringBuilder from the string, call reverse(), and convert it back to a String. Compare this reversed string with the original string using the equals() method. This is a concise way to check for palindromes.
8. Find All Permutations of a String
Why you might get asked this:
A classic recursion problem demonstrating understanding of backtracking and generating combinatorial sequences.
How to answer:
Use a recursive function. For each character in the string, swap it with the first character and recursively find permutations of the remaining substring.
Example answer:
Implement a recursive helper function that takes the string and current left and right indices. The base case is when left equals right; print the string. Otherwise, loop from left to right, swap the character at left with the character at i, recurse, and then swap back (backtrack).
9. Find the Maximum Subarray Sum
Why you might get asked this:
Evaluates understanding of dynamic programming concepts or the specific Kadane's algorithm for efficiently solving this problem.
How to answer:
Use Kadane's algorithm: maintain two variables, one for the maximum sum ending at the current position and one for the overall maximum sum found so far.
Example answer:
Initialize maxsofar and maxendinghere to the first element. Iterate through the array starting from the second element. Update maxendinghere to be the maximum of the current element or the current element plus maxendinghere. Update maxsofar to be the maximum of maxsofar and maxendinghere.
10. Implement a Binary Search Algorithm
Why you might get asked this:
A fundamental search algorithm question testing recursive or iterative implementation skills and understanding of sorted data.
How to answer:
Use an iterative approach with low and high pointers. While low <= high, calculate the middle index. Compare the target with the middle element and adjust low or high accordingly.
Example answer:
Initialize 'left' to 0 and 'right' to the array length minus 1. While left is less than or equal to right, calculate the middle index. If the element at mid is the target, return mid. If it's less, set left to mid + 1. If it's greater, set right to mid - 1. If the loop finishes, return -1.
11. Find the First Non-Repeated Character in a String
Why you might get asked this:
Tests string processing and the use of frequency maps (HashMaps) for counting occurrences efficiently.
How to answer:
Use a frequency map (HashMap
) to store character counts. Iterate through the string once to populate the map, then iterate again to find the first character with a count of 1.
Example answer:
Create a HashMap to store character counts. Iterate through the string, updating the count for each character in the map. Then, iterate through the string again. The first character whose count in the map is 1 is the answer.
12. Sort an Array Using QuickSort
Why you might get asked this:
Evaluates understanding of recursive sorting algorithms, pivot selection, and partitioning techniques.
How to answer:
Implement the recursive function and the partition helper function. Choose a pivot, partition the array around the pivot, and recursively sort the sub-arrays.
Example answer:
Implement a quickSort function that takes the array and low/high indices. If low < high, call a partition function to rearrange elements and get the pivot index. Recursively call quickSort for the left and right sub-arrays around the pivot.
13. Find the Middle Element of a Linked List
Why you might get asked this:
A classic linked list problem testing pointer manipulation and the "fast and slow pointer" technique.
How to answer:
Use two pointers: one moves one step at a time (slow), and the other moves two steps (fast). When the fast pointer reaches the end, the slow pointer will be at the middle.
Example answer:
Initialize a slow pointer and a fast pointer both to the head of the list. Loop while the fast pointer and its next are not null. In each iteration, move slow one step (slow = slow.next) and fast two steps (fast = fast.next.next). When the loop ends, slow is at the middle node.
14. Merge Two Sorted Arrays
Why you might get asked this:
Tests the ability to merge sorted sequences efficiently, typically using a two-pointer approach without extra space (or using a third array).
How to answer:
Use a two-pointer technique to iterate through both arrays simultaneously, comparing elements and placing the smaller one into a result array. Handle remaining elements from either array.
Example answer:
Create a new array to hold the merged result. Use three pointers: one for each input array (i, j) and one for the result array (k). While both i and j are within bounds, compare arr1[i] and arr2[j], copy the smaller to result[k], and increment the corresponding source pointer and k. Copy any remaining elements from arr1 or arr2.
15. Check if a Number is a Power of Two
Why you might get asked this:
Assesses understanding of bitwise operations, which offer an elegant and efficient solution.
How to answer:
Explain the property that a power of two in binary has only one '1' bit, and demonstrate how n > 0 && (n & (n - 1)) == 0
checks this.
Example answer:
A positive integer is a power of two if and only if its binary representation has exactly one bit set to 1. The bitwise AND operation n & (n - 1)
clears the lowest set bit in n. If n is a power of two, n-1 will have all bits below the original set bit as 1, and the original set bit as 0. The AND result is 0. Ensure n is positive.
16. Find the Substring with the Maximum Length
Why you might get asked this:
A sliding window problem testing efficient substring processing and using a set to track unique characters.
How to answer:
Use a sliding window approach with two pointers (start and end) and a HashSet
to keep track of characters within the current window. Expand the window, removing characters from the start if duplicates are found.
Example answer:
Initialize max length to 0, window start to 0, and an empty HashSet. Iterate with window end. While the character at window end is in the set, remove the character at window start from the set and increment window start. Add the character at window end to the set. Update max length with the current window size (end - start + 1).
17. Find All Possible Combinations of a Given Array
Why you might get asked this:
Another recursive problem demonstrating backtracking for generating subsets or combinations.
How to answer:
Use recursion. A helper function can build combinations by either including or excluding the current element, or by selecting elements sequentially.
Example answer:
Implement a recursive function that takes the array, a temporary combination array, current index, end index, and target size 'r'. The base case is when the temporary combination is filled (index == r), print it. Otherwise, include the current element (at start index), recurse with incremented index and start+1. Then, exclude the current element and recurse with incremented start but the same index.
18. Check if Two Strings are Anagrams
Why you might get asked this:
Tests string manipulation, sorting, or frequency counting techniques to determine if two strings have the same characters with the same counts.
How to answer:
Method 1: Sort both strings after cleaning (removing spaces, lowercase) and compare them. Method 2: Use a frequency map (array or HashMap) to count character occurrences in both strings and compare maps.
Example answer:
Clean both strings by removing spaces and converting to lowercase. Convert them to character arrays and sort both arrays. Finally, compare the sorted character arrays using Arrays.equals()
. If they are equal, the strings are anagrams.
19. Find the Frequency of Each Character in a String
Why you might get asked this:
A common string processing task that demonstrates the use of frequency maps (HashMap
or an array for ASCII characters).
How to answer:
Use a HashMap
to store character-frequency pairs. Iterate through the string, incrementing the count for each character in the map.
Example answer:
Create an empty HashMap. Iterate through each character of the input string. For each character, check if it exists as a key in the map. If yes, get its current count and increment it, putting it back. If not, add the character to the map with a count of 1.
20. Check if a String Contains Only Digits
Why you might get asked this:
Evaluates basic string validation skills, often solvable using regular expressions or character-by-character checking.
How to answer:
Use the String.matches()
method with a regular expression \\d+
or iterate through the string, checking Character.isDigit()
for each character.
Example answer:
Use the String.matches()
method with the regular expression "\\d+". This regex checks if the entire string consists of one or more digits. This is a clean and standard Java approach for this validation.
21. Bubble Sort Algorithm
Why you might get asked this:
A fundamental sorting algorithm question, often used to check understanding of basic comparison-based sorting logic, though not efficient.
How to answer:
Implement nested loops. The outer loop controls passes, and the inner loop compares adjacent elements, swapping them if they are in the wrong order.
Example answer:
Use nested loops. The outer loop runs from i=0 to n-2. The inner loop runs from j=0 to n-i-2. Inside the inner loop, compare array[j] and array[j+1]. If array[j] > array[j+1], swap them.
22. Find the Missing Number in an Array (1 to n)
Why you might get asked this:
Tests basic array manipulation and mathematical thinking (using sum formula) or bitwise logic (using XOR).
How to answer:
Method 1: Calculate the expected sum of numbers from 1 to n using the formula n*(n+1)/2 and subtract the actual sum of elements in the array. Method 2: Use XOR.
Example answer:
Calculate the expected sum of numbers from 1 to n (where n is array.length + 1) using the formula n*(n+1)/2. Calculate the actual sum of all numbers in the given array. The missing number is the expected sum minus the actual sum.
23. Find the Kth Smallest Element in an Unsorted Array
Why you might get asked this:
Evaluates understanding of sorting algorithms, partitioning (QuickSelect), or using data structures like priority queues.
How to answer:
Method 1: Sort the array and return the element at index k-1. Method 2: Use a min-heap (priority queue) of size k. Method 3: Use QuickSelect (average O(n)).
Example answer:
The simplest way is to sort the array using Arrays.sort()
. Once sorted, the kth smallest element will be located at index k-1 (assuming k is 1-based). Return arr[k-1].
24. Check if a Binary Tree is Balanced
Why you might get asked this:
A recursive tree problem testing understanding of tree traversal and height calculations to meet the balanced definition (height difference of left and right subtrees <= 1).
How to answer:
Use a recursive helper function that calculates the height of subtrees. If at any node the height difference is > 1, return -1 (indicating imbalance). Otherwise, return the height of the current subtree.
Example answer:
Implement a recursive helper function checkHeight
that returns the height if balanced, and -1 if unbalanced. checkHeight
calculates heights of left and right children. If either is -1, return -1. If abs(leftHeight - rightHeight) > 1
, return -1. Otherwise, return max(leftHeight, rightHeight) + 1
. The main function calls checkHeight
on the root and checks if the result is -1.
25. Find the Most Frequent Element in an Array
Why you might get asked this:
Tests array traversal and the use of frequency maps (HashMap
) to count occurrences and find the maximum count.
How to answer:
Use a HashMap
to store element frequencies. Iterate through the array, updating counts in the map. While doing so, keep track of the element with the highest frequency seen so far.
Example answer:
Create a HashMap to store frequencies. Iterate through the array. For each number, update its count in the map using getOrDefault. Keep track of the maximum count encountered and the element corresponding to that count. Return the element with the maximum count.
26. Check if a Number is Perfect
Why you might get asked this:
A number theory problem testing basic loop and divisibility logic.
How to answer:
Calculate the sum of all positive divisors of the number (excluding the number itself). If the sum equals the number, it is perfect.
Example answer:
Initialize a sum variable to 0. Loop from 1 up to (but not including) the number. Inside the loop, check if the number is divisible by the current loop variable. If it is, add the loop variable to the sum. After the loop, check if the sum equals the original number.
27. Remove Duplicates from an Array
Why you might get asked this:
Tests array manipulation and the use of data structures like HashSet
or sorting to identify and remove duplicates.
How to answer:
Method 1: Use a HashSet
to store unique elements encountered during traversal, then convert the set back to an array. Method 2: If modifying the original array in-place is allowed for sorted arrays, use a two-pointer approach.
Example answer:
Create a HashSet. Iterate through the input array and add each element to the set. The HashSet automatically handles uniqueness. Then, create a new array with the size of the set. Iterate through the elements in the set and copy them into the new array. Return the new array.
28. Find All Substrings of a String
Why you might get asked this:
Tests nested loop control and understanding of string slicing/substring methods.
How to answer:
Use nested loops. The outer loop iterates through all possible starting indices, and the inner loop iterates through all possible ending indices from the start index onwards.
Example answer:
Use two nested loops. The outer loop iterates from i = 0 to string.length() - 1 (start index). The inner loop iterates from j = i + 1 to string.length() (end index, exclusive in substring). Inside the inner loop, print the substring using str.substring(i, j)
.
29. Check if a String is a Subsequence of Another String
Why you might get asked this:
Tests string traversal and the efficient two-pointer technique for checking ordered character existence.
How to answer:
Use a two-pointer approach, one pointer for each string. Iterate through the second string, incrementing the first string's pointer only when a matching character is found. If the first string's pointer reaches its end, it is a subsequence.
Example answer:
Initialize two pointers, i for the first string (s1) and j for the second string (s2), both starting at 0. Loop while both i and j are within their string bounds. If s1.charAt(i) == s2.charAt(j), increment i. Always increment j. After the loop, if i equals s1.length(), s1 is a subsequence.
30. Find the Pair with a Given Sum in an Array
Why you might get asked this:
Evaluates array traversal and the use of a HashMap
for efficient lookups (O(n)) to find complementary pairs.
How to answer:
Use a HashMap
. Iterate through the array. For each element, check if the complement (target - element) exists in the map. If yes, a pair is found. If not, add the current element to the map.
Example answer:
Create an empty HashMap. Iterate through the array. For each number, calculate the complement (targetSum - current number). Check if the complement exists as a key in the map. If it does, return true. If not, put the current number into the map. If the loop finishes without finding a pair, return false.
Other Tips to Prepare for a Java Coding Interview
Beyond practicing specific java coding interview questions, robust preparation involves understanding the underlying concepts. Don't just memorize solutions; learn the logic and consider alternative approaches and their trade-offs (time/space complexity). As famously quoted, "The best way to predict the future is to invent it." In interviews, this means being proactive in explaining your thought process and asking clarifying questions. Practice coding on a whiteboard or shared editor to simulate the interview environment. Use tools like the Verve AI Interview Copilot https://vervecopilot.com to get real-time feedback and refine your responses to common java coding interview questions. The Verve AI Interview Copilot can help you structure your answers and gain confidence. Leverage the Verve AI Interview Copilot to practice articulating your solutions clearly and efficiently. Regular practice, combined with understanding core Java concepts and data structures, is your path to success in any java coding interview.
Frequently Asked Questions
Q1: How much Java theory is needed? A1: While coding is key, understand core Java concepts like OOP, collections, and concurrency.
Q2: Should I focus on algorithms or data structures for java coding interview questions? A2: Both are crucial. Algorithms often rely on choosing the right data structure for efficiency.
Q3: How do I practice java coding interview questions effectively? A3: Start with basics, then progress to harder problems. Practice coding them cleanly and discussing complexity.
Q4: Is it okay to ask questions during a java coding interview? A4: Absolutely! Clarifying requirements shows good communication and problem-solving skills.
Q5: What is the best way to handle edge cases in java coding interview questions? A5: Think about empty inputs, nulls, zeros, and extreme values during the planning stage and test your code against them.
Q6: What resources are good for practicing java coding interview questions? A6: LeetCode, HackerRank, Cracking the Coding Interview book, and tools like Verve AI Interview Copilot are excellent.