Java Coding Interview Questions

Okan Özşahin
5 min readFeb 26, 2024

--

Navigating Java programming interviews can be daunting, but mastering fundamental concepts is key to success. In this article, we demystify Java interview questions by delving into essential coding challenges that illuminate core principles. From exploring the immutability of String objects to crafting algorithms for factorial calculations or maximum subarray detection, each code example serves as a gateway to Java mastery. Our goal is to equip readers with the knowledge and confidence necessary to excel in Java programming interviews while fostering a deeper understanding of the language’s fundamental concepts. Join us on this journey as we unravel the mysteries of Java coding interviews and dive deep into the heart of Java programming.

1. Write a program to reverse a string in Java.

public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder();

for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}

return reversed.toString();
}

2. Write a program to find the largest number in an array in Java.

public static int findLargestNum(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("Array must not be empty or null");
}

int largest = arr[0]; // Assume the first element is the largest

for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

return largest;
}

3. Write a program to check if a given number is prime in Java.

public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}

// Check divisibility up to the square root of the number
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}

return true;
}

4. Write a program to find the factorial of a given number in Java.

public static long calculateFact(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative numbers");
}

long factorial = 1;

for (int i = 1; i <= n; i++) {
factorial *= i;
}

return factorial;
}

5. Write a program to remove duplicate elements from an array in Java.

public static int[] removeDuplicates(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}

Set<Integer> set = new HashSet<>();

// Add elements to the Set (duplicates will automatically be removed)
for (int num: arr) {
set.add(num);
}

int[] uniqueArr = new int[set.size()];
int idx = 0;

for (int n: set) {
uniqueArr[idx++] = n;
}

return uniqueArr;
}

6. Write a program to find the second largest number in an array in Java.

public static int findSecondLargest(int[] arr) {
if (arr == null || arr.length < 2) {
throw new IllegalArgumentException("Array must have at least two elements");
}

int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;

for (int num : arr) {
if (num > max) {
secondMax = max;
max = num;
} else if (num > secondMax && num != max) {
secondMax = num;
}
}

if (secondMax == Integer.MIN_VALUE) {
throw new IllegalArgumentException("No second largest element found");
}

return secondMax;
}

7. Write a program to check if two strings are anagrams in Java.

public static boolean areAnagrams(String s1, String s2) {
// Remove space and convert to lowercase
s1 = s1.replaceAll("\\s", "").toLowerCase();
s2 = s2.replaceAll("\\s", "").toLowerCase();

if (s1.length() != s2.length()) {
return false;
}

char[] cArr1 = s1.toCharArray();
char[] cArr2 = s2.toCharArray();
Arrays.sort(cArr1);
Arrays.sort(cArr2);

return Arrays.equals(cArr1, cArr2);
}

8. Write a program to find the first non-repeating character in a string in Java.

public static char findFirstNonRepeatingChar(String s) {
int[] freq = new int[256]; // Assuming ASCII

// First pass to store frequencies
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i)]++;
}

// Second pass to find the first non-repeating char
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i)] == 1) {
return s.charAt(i);
}
}
return '\0'; // Return '\0' if no non-repeating character is found
}

9. Write a program to check if a given string is a palindrome in Java.

public static boolean isPalindrome(String s) {
// Normalize the string: remove non-alphanumeric characters and convert to lower case
String normalizedStr = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();

int left = 0; // Start poiner
int right = normalizedStr.length() - 1; // End pointer

while (left < right) {
if (normalizedStr.charAt(left) != normalizedStr.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

10. Write a program to find the minimum number of coins needed to make change for a given amount in Java.

public static int coinChange(int[] coins, int amount) {
// dp[i] will be storing min number of coins required for i value.
// So dp[amount] will have result.
int[] dp = new int[amount + 1];

for (int i = 1; i <= amount; i++) {
dp[i] = Integer.MAX_VALUE;
}

// Base case (if given value amount is 0)
dp[0] = 0;

for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if (coins[j] <= i) {
int sub_res = dp[i - coins[j]];
if (sub_res != Integer.MAX_VALUE && sub_res + 1 < dp[i]) {
dp[i] = sub_res + 1;
}
}
}
}
return dp[amount] != Integer.MAX_VALUE ? dp[amount] : -1;
}

11. Write a program to find the maximum sum subarray in an array in Java.

public static int maxSubArray(int[] arr) {
int currSum = arr[0];
int maxSum = arr[0];

for (int i = 1; i < arr.length; i++) {
currSum = Math.max(arr[i], currSum + arr[i]);
maxSum = Math.max(currSum, maxSum);
}

return maxSum;
}

12. Write a program to find the nth Fibonacci number in Java.

public static int fibonacci(int n) {
if (n <= 1) {
return n;
}

return fibonacci(n - 1) + fibonacci(n - 2);
}

13. Write a program to swap two numbers without using a third variable in Java.

b = b + a; // now b is sum of both the numbers
a = b - a; // b - a = (b + a) - a = b (a is swapped)
b = b - a; // (b + a) - b = a (b is swapped)

14. Write a program to get distinct characters and their count in a string in Java.

public static Map<Character, Integer> getCharacterCounts(String str) {
Map<Character, Integer> charCounts = new HashMap<>();

for (char c : str.toCharArray()) {
// Ignore spaces
if (c != ' ') {
charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);
}
}

return charCounts;
}

15. Prove that a String object in Java is immutable programmatically?

String s1 = "Java";
String s2 = s1;
// proof that s1 and s2 have the same reference
System.out.println(s1 == s2);

s1 = "Python";
// proof that s1 and s2 have different reference
System.out.println(s1 == s2);
System.out.println(s2);
// prints "Java" supporting the fact that original String value is unchanged,
// hence String is immutable

--

--

Okan Özşahin

Backend Developer at hop | Civil Engineer | MS Computer Engineering