Java Interview Questions
In this page:
String Reversal
Reversing a string is commonly implemented by converting it to a char[], swapping characters from both ends inward, or simply calling new StringBuilder(str).reverse() for the built-in shortcut.
Example: String Reversal
public class Main {
public static void main(String[] args) {
String text = "hello";
System.out.println(new StringBuilder(text).reverse());
}
}
Login to try C/C++/Java/PHP code in the editor
Palindrome Check
A palindrome check compares a string against its own reverse, or walks inward from both ends simultaneously comparing characters — the same underlying idea just implemented two different ways.
Example: Palindrome Check
public class Main {
static boolean isPalindrome(String s) {
return s.equals(new StringBuilder(s).reverse().toString());
}
public static void main(String[] args) {
System.out.println(isPalindrome("racecar"));
}
}
Login to try C/C++/Java/PHP code in the editor
Finding Duplicates
Finding duplicates in a collection is typically solved by tracking seen elements in a HashSet: if an element is already present when you try to add it, you've found a duplicate.
Example: Finding Duplicates
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 2};
HashSet<Integer> seen = new HashSet<>();
for (int n : nums) {
if (!seen.add(n)) {
System.out.println("Duplicate: " + n);
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
The FizzBuzz Problem
FizzBuzz — printing Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both — is a classic beginner interview problem testing basic control flow and the modulo operator.
Example: The FizzBuzz Problem
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 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);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Counting Character Frequencies
Counting character frequencies usually uses a HashMap<Character, Integer>, incrementing each character's count as you scan through the string once.
Example: Counting Character Frequencies
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String text = "hello";
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : text.toCharArray()) {
freq.merge(c, 1, Integer::sum);
}
System.out.println(freq);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: