Preparing for a Java coding interview can be both exciting and daunting. To help you get ready, we’ve compiled a list of common Java interview coding questions along with brief explanations and tips on how to approach them. Whether you’re a beginner or looking to refresh your skills, practicing these questions will boost your confidence and improve your coding proficiency.
1. Reverse a String
Problem
Write a method that takes a string as input and returns the string reversed.
Example
Input: "hello" Output: "olleh"
Solution
public String reverseString(String str) { return new StringBuilder(str).reverse().toString(); }
Tips
- Consider edge cases, such as empty strings or null inputs.
2. Check for Palindrome
Problem
Write a method to check if a given string is a palindrome (reads the same backward as forward).
Example
Input: "racecar" Output: true Input: "hello" Output: false
Solution
public boolean isPalindrome(String str) { String reversed = new StringBuilder(str).reverse().toString(); return str.equals(reversed); }
Tips
- Optimize for case insensitivity and ignore non-alphanumeric characters.
3. FizzBuzz
Problem
Write a method that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers which are multiples of both three and five, print “FizzBuzz”.
Solution
public void fizzBuzz() { for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { System.out.println("FizzBuzz"); } else if (i % 3 == 0) { System.out.println("Fizz"); } else if (i % 5 == 0) { System.out.println("Buzz"); } else { System.out.println(i); } } }
Tips
- Focus on clean, readable code and efficient use of conditional statements.
4. Find the First Non-Repeating Character
Problem
Given a string, find the first non-repeating character and return its index. If it doesn’t exist, return -1.
Example
Input: "leetcode" Output: 0 Input: "loveleetcode" Output: 2
Solution
public int firstUniqChar(String s) { Map<Character, Integer> charCount = new HashMap<>(); for (char c : s.toCharArray()) { charCount.put(c, charCount.getOrDefault(c, 0) + 1); } for (int i = 0; i < s.length(); i++) { if (charCount.get(s.charAt(i)) == 1) { return i; } } return -1; }
Tips
- Utilize a HashMap to count character occurrences efficiently.
5. Merge Two Sorted Arrays
Problem
Given two sorted arrays, merge them into a single sorted array.
Example
Input: [1, 3, 5], [2, 4, 6] Output: [1, 2, 3, 4, 5, 6]
Solution
public int[] mergeArrays(int[] arr1, int[] arr2) { int[] merged = new int[arr1.length + arr2.length]; int i = 0, j = 0, k = 0; while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { merged[k++] = arr1[i++]; } else { merged[k++] = arr2[j++]; } } while (i < arr1.length) { merged[k++] = arr1[i++]; } while (j < arr2.length) { merged[k++] = arr2[j++]; } return merged; }
Tips
- Maintain clarity in your logic by using pointers to traverse both arrays.
6. Find the Maximum Subarray Sum (Kadane’s Algorithm)
Problem
Given an integer array, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example
Input: [-2,1,-3,4,-1,2,1,-5,4] Output: 6 // The subarray [4,-1,2,1] has the largest sum.
Solution
public int maxSubArray(int[] nums) { int maxSoFar = nums[0]; int currentMax = nums[0]; for (int i = 1; i < nums.length; i++) { currentMax = Math.max(nums[i], currentMax + nums[i]); maxSoFar = Math.max(maxSoFar, currentMax); } return maxSoFar; }
Tips
- Understand the principles of dynamic programming and optimal substructure.
7. Calculate Factorial (Iterative and Recursive)
Problem
Write a method to calculate the factorial of a given number.
Example
Input: 5 Output: 120
Solution (Iterative)
public int factorialIterative(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
Solution (Recursive)
public int factorialRecursive(int n) { if (n == 0) { return 1; } return n * factorialRecursive(n - 1); }
Tips
- Understand both iterative and recursive approaches to deepen your understanding of function calls.
8. Count Vowels in a String
Problem
Write a method to count the number of vowels in a given string.
Example
Input: "hello world" Output: 3
Solution
public int countVowels(String str) { int count = 0; for (char c : str.toLowerCase().toCharArray()) { if ("aeiou".indexOf(c) != -1) { count++; } } return count; }
Tips
- Consider edge cases such as uppercase letters and special characters.
9. Check if Two Strings are Anagrams
Problem
Write a method to determine if two strings are anagrams of each other.
Example
Input: "listen", "silent" Output: true
Solution
public boolean areAnagrams(String str1, String str2) { if (str1.length() != str2.length()) return false; char[] arr1 = str1.toCharArray(); char[] arr2 = str2.toCharArray(); Arrays.sort(arr1); Arrays.sort(arr2); return Arrays.equals(arr1, arr2); }
Tips
- Utilize sorting to simplify the comparison of character frequencies.
10. Implement a Basic Calculator
Problem
Write a method to evaluate a simple mathematical expression given as a string.
Example
Input: "3 + 5" Output: 8
Solution
This problem can be complex, but a simple implementation might look like this:
public int simpleCalculator(String expression) { String[] tokens = expression.split(" "); int num1 = Integer.parseInt(tokens[0]); String operator = tokens[1]; int num2 = Integer.parseInt(tokens[2]); switch (operator) { case "+": return num1 + num2; case "-": return num1 - num2; case "*": return num1 * num2; case "/": return num1 / num2; default: throw new UnsupportedOperationException("Invalid operator"); } }
Tips
- Handle various operators and consider extending the logic for parentheses and order of operations.
Conclusion
Practicing these Java coding interview questions will help you sharpen your problem-solving skills and prepare you for a variety of scenarios during interviews. Focus on writing clean, efficient code, and don’t forget to test your solutions with edge cases. Good luck with your preparations.