Programs every Java candidate should write fluently
Interviewers judge clean logic, edge cases and complexity — and increasingly ask for a Java 8 stream version too. Practise both styles.
- StringsReverse, palindrome, duplicates and anagrams.
- NumbersFibonacci, primes and missing numbers.
- StreamsgroupingBy, counting and sorting entries.
These are the Java programs asked most often in campus drives and service-company interviews, each with a clean classic solution and, where it helps, a Java 8+ stream version. Practise writing them without an IDE — many interviews use a plain editor.
1. Reverse a string without using reverse().
Swap characters from both ends of a char array (O(n), in place on the array). Mention new StringBuilder(s).reverse() as the practical answer.
static String reverse(String s) {
char[] c = s.toCharArray();
for (int i = 0, j = c.length - 1; i < j; i++, j--) {
char t = c[i]; c[i] = c[j]; c[j] = t;
}
return new String(c);
}2. Check whether a string is a palindrome (ignore case and spaces).
Two pointers that skip non-alphanumeric characters — O(n) time, O(1) extra space.
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--))) return false;
}
return true;
}3. Find duplicate characters and their counts.
Count with a LinkedHashMap (keeps first-seen order) or with streams and groupingBy.
static Map<Character, Long> duplicates(String s) {
return s.chars()
.mapToObj(c -> (char) c)
.filter(Character::isLetter)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
}
// duplicates("programming") -> {r=2, g=2, m=2}4. Check whether two strings are anagrams.
Count letters with an int array of size 26 (O(n)) — faster than sorting (O(n log n)).
static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}5. Print the first n Fibonacci numbers and check if a number is prime.
Iterative Fibonacci with two variables (O(n)); prime check up to the square root, skipping even numbers.
static void fibonacci(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
long next = a + b; a = b; b = next;
}
}
static boolean isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
for (int d = 3; (long) d * d <= n; d += 2) if (n % d == 0) return false;
return true;
}6. Find the second highest number in an array.
One pass with two variables, ignoring duplicates of the maximum. Or a stream: distinct, sort descending, skip one.
static OptionalInt secondHighest(int[] nums) {
Integer first = null, second = null;
for (int x : nums) {
if (first == null || x > first) { second = first; first = x; }
else if (x != first && (second == null || x > second)) second = x;
}
return second == null ? OptionalInt.empty() : OptionalInt.of(second);
}
// stream version
Arrays.stream(nums).boxed().distinct().sorted(Comparator.reverseOrder()).skip(1).findFirst();7. Count word frequency in a sentence and print the top 3.
Split on whitespace, normalise case, count with groupingBy, then sort entries by count.
String text = "the cat and the hat and the bat";
Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\s+"))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
freq.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(3)
.forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
// the = 3, and = 2, cat = 18. Swap two numbers without a third variable, and find the missing number in 1..n.
Arithmetic or XOR swap; for the missing number, expected sum minus actual sum — use long to avoid overflow for large n.
int a = 5, b = 9;
a = a ^ b; b = a ^ b; a = a ^ b; // a = 9, b = 5
static int missing(int[] nums, int n) {
long expected = (long) n * (n + 1) / 2;
long actual = 0;
for (int x : nums) actual += x;
return (int) (expected - actual);
}Remember
Key points
- Two pointers for strings
O(n) time, O(1) extra space.
- int[26] for letter counts
Faster than sorting.
- Use long for sums
Avoid integer overflow.
- Know the stream version
groupingBy + counting is asked often.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 Reverse each word of a sentence but keep word order. Basic
Split on spaces, reverse each word with StringBuilder, join with spaces.
String result = Arrays.stream(s.split(" ")) .map(w -> new StringBuilder(w).reverse().toString()) .collect(Collectors.joining(" ")); -
2 Find the first non-repeated character. Basic
Count with a LinkedHashMap, then return the first key with count 1.
-
3 Remove duplicates from an array while keeping order. Basic
Add elements to a
LinkedHashSet, orArrays.stream(a).distinct().toArray(). -
4 Check whether a number is an Armstrong number. Basic
Sum each digit raised to the number of digits and compare with the original.
-
5 Find a pair of numbers with a given sum. Intermediate
Use a HashSet of seen numbers: for each x, check whether
target - xwas seen — O(n). -
6 Count vowels and consonants in a string. Basic
Loop over letters, check membership in "aeiou" after lower-casing, count the rest as consonants.
-
7 Find the factorial of a large number like 50. Intermediate
Use
BigInteger, since 50! overflows long.BigInteger f = BigInteger.ONE; for (int i = 2; i <= 50; i++) f = f.multiply(BigInteger.valueOf(i));