Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training
Java Ecosystem⏱️ 14 min readπŸ“… Nov 20

30 Java Coding Interview Programs With Solutions (2026)

VS
Vikas Sharmaβ€’Senior Java Developer
πŸ“‘ Contents (42 sections)

πŸ“ŒHow to Use These Programs

Service companies, product companies and GCCs in India still open Java interviews with live coding. The questions repeat: string manipulation, arrays, number puzzles, collections, streams and a little concurrency. Interviewers watch how you reason, name things and handle edge cases, not just whether the code compiles.

For each program below, first solve it yourself, then compare. Say the time complexity out loud. Pair this list with the concept questions in Java interview questions, and if you are aiming at backend roles, Spring Boot interview questions.

πŸ“ŒStrings

1. Reverse a string

String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}

Be ready to do it manually with a char array and two pointers as well.

2. Check a palindrome

boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i++) != s.charAt(j--)) return false;
}
return true;
}

3. Check if two strings are anagrams

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;
}

O(n) time, O(1) space for lowercase letters.

4. Count character frequency

Map<Character, Integer> freq(String s) {
Map<Character, Integer> m = new HashMap<>();
for (char c : s.toCharArray()) m.merge(c, 1, Integer::sum);
return m;
}

5. First non-repeating character

Character firstUnique(String s) {
Map<Character, Integer> m = new LinkedHashMap<>();
for (char c : s.toCharArray()) m.merge(c, 1, Integer::sum);
for (var e : m.entrySet()) if (e.getValue() == 1) return e.getKey();
return null;
}

LinkedHashMap keeps insertion order, which is the point of the question.

6. Reverse the words in a sentence

String reverseWords(String s) {
List<String> words = Arrays.asList(s.trim().split("\\s+"));
Collections.reverse(words);
return String.join(" ", words);
}

7. Count vowels and consonants

int[] vowelsConsonants(String s) {
int v = 0, c = 0;
for (char ch : s.toLowerCase().toCharArray()) {
if (!Character.isLetter(ch)) continue;
if ("aeiou".indexOf(ch) >= 0) v++; else c++;
}
return new int[]{v, c};
}

8. Remove duplicate characters, keeping order

String dedupe(String s) {
Set<Character> seen = new LinkedHashSet<>();
for (char c : s.toCharArray()) seen.add(c);
StringBuilder sb = new StringBuilder();
seen.forEach(sb::append);
return sb.toString();
}

πŸ“ŒNumbers

9. Fibonacci series

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;
}
}

Mention that the naive recursive version is exponential and memoisation fixes it.

10. Check a prime number

boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false;
return true;
}

Checking up to the square root gives O(sqrt n).

11. Factorial

long factorial(int n) {
long r = 1;
for (int i = 2; i <= n; i++) r *= i;
return r;
}

Point out overflow beyond 20 and suggest BigInteger.

12. Armstrong number

boolean isArmstrong(int n) {
int digits = String.valueOf(n).length(), sum = 0, x = n;
while (x > 0) { sum += (int) Math.pow(x % 10, digits); x /= 10; }
return sum == n;
}

13. Swap two numbers without a temp variable

a = a + b;
b = a - b;
a = a - b;

Mention the overflow risk, and the XOR alternative.

14. Reverse an integer

int reverse(int n) {
int r = 0;
while (n != 0) { r = r * 10 + n % 10; n /= 10; }
return r;
}

15. GCD of two numbers

int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}

πŸ“ŒArrays

16. Find duplicates in an array

Set<Integer> duplicates(int[] arr) {
Set<Integer> seen = new HashSet<>(), dup = new HashSet<>();
for (int x : arr) if (!seen.add(x)) dup.add(x);
return dup;
}

17. Find the missing number from 1 to n

int missing(int[] arr, int n) {
long expected = (long) n * (n + 1) / 2, sum = 0;
for (int x : arr) sum += x;
return (int) (expected - sum);
}

18. Second largest element

int secondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) second = x;
}
return second;
}

19. Two sum

int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> idx = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = idx.get(target - nums[i]);
if (j != null) return new int[]{j, i};
idx.put(nums[i], i);
}
return new int[0];
}

O(n) with a HashMap instead of O(n squared) with two loops. Practise more problems like this on our free DSA practice page.

20. Move all zeros to the end

void moveZeros(int[] a) {
int k = 0;
for (int x : a) if (x != 0) a[k++] = x;
while (k < a.length) a[k++] = 0;
}

21. Rotate an array by k

void rotate(int[] a, int k) {
k %= a.length;
reverse(a, 0, a.length - 1);
reverse(a, 0, k - 1);
reverse(a, k, a.length - 1);
}
void reverse(int[] a, int i, int j) {
while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}

22. Merge two sorted arrays

int[] merge(int[] a, int[] b) {
int[] r = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) r[k++] = a[i] <= b[j] ? a[i++] : b[j++];
while (i < a.length) r[k++] = a[i++];
while (j < b.length) r[k++] = b[j++];
return r;
}

πŸ“ŒCollections and Streams

23. Group employees by department with streams

Map<String, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::department));

24. Average salary per department

Map<String, Double> avg = employees.stream()
.collect(Collectors.groupingBy(Employee::department,
Collectors.averagingDouble(Employee::salary)));

25. Highest paid employee in each department

Map<String, Optional<Employee>> top = employees.stream()
.collect(Collectors.groupingBy(Employee::department,
Collectors.maxBy(Comparator.comparingDouble(Employee::salary))));

26. Word frequency, sorted by count

Map<String, Long> counts = Arrays.stream(text.toLowerCase().split("\\W+"))
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
counts.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(5)
.forEach(System.out::println);

27. Sort a map by value

LinkedHashMap<String, Integer> sorted = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(x, y) -> x, LinkedHashMap::new));

28. LRU cache using LinkedHashMap

class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LRUCache(int capacity) {
super(capacity, 0.75f, true); // access order
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}

Explain the access-order flag. A follow-up often asks you to build it with a HashMap and a doubly linked list.

πŸ“ŒConcurrency

29. Thread-safe singleton

class Config {
private Config() {}
private static class Holder {
static final Config INSTANCE = new Config();
}
static Config getInstance() { return Holder.INSTANCE; }
}

The holder idiom is lazy and thread-safe without synchronisation. Also know double-checked locking with a volatile field, and the enum singleton.

30. Producer-consumer with BlockingQueue

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
Thread producer = new Thread(() -> {
try { for (int i = 0; i < 100; i++) queue.put(i); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
try { while (true) System.out.println(queue.take()); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start();
consumer.start();

put blocks when the queue is full and take blocks when it is empty, so no manual wait and notify is needed. Be ready to also write the wait and notify version, and to mention virtual threads in Java 21 for high-concurrency IO work.

πŸ“ŒWhat Interviewers Look For

  • Edge cases: empty input, null, a single element, negative numbers, overflow
  • Complexity: state time and space for every solution
  • Clean names: small methods and meaningful variable names
  • Modern Java: streams, records, var and switch expressions where they help readability, not everywhere
  • Testing: say which inputs you would test with
  • πŸ“ŒFAQ

    Are these enough to clear a Java interview?

    They cover the live coding round for most service and mid-size product companies. Product companies add DSA problems on trees, graphs and dynamic programming, and experienced roles add Spring Boot, microservices and system design.

    Should I use streams or loops in interviews?

    Use whichever is clearest. Streams are great for grouping and aggregation; plain loops are often clearer for index-based array problems. Interviewers want to see you choose deliberately.

    How do I practise effectively?

    Write each program from scratch in a plain editor, time yourself, then explain it aloud. Follow the Java developer roadmap for what to learn around these programs.

    πŸ“ŒLearn It Live

    Prakalpana's Java course is taught live online with an optional 1-on-1 track, daily coding practice, code reviews and mock interviews. See the complete Java track, from core Java to Spring Boot and microservices. WhatsApp or call +91 9180377502 for a free demo.

    VS

    Written by

    Vikas Sharma

    Senior Java Developer

    πŸš€ Master Java Ecosystem

    Live online + 1-on-1 Java Programming training Β· Join 5000+ developers

    Not sure what to do? Book career counselling (β‚Ή200 / 30 min)

    Not sure what to learn next?

    A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

    1. 1Discuss your goals
    2. 2Get a personal plan
    3. 3Start learning
    Book for β‚Ή200/ 30 min