Java Coding programs for interviews

Almost every automation and SDET interview includes a coding round: reverse a string, remove duplicates, find the second largest number, find a pair with a given sum. These are not hard algorithm puzzles — they test whether you can write clean Core Java under pressure, handle edge cases, and explain your approach.

This guide gives you everything for that round: the six patterns behind most questions (with tested code), the complete index of array, number, string and matrix programs on this site, how interviewers score your answer, and a four-week practice plan.

Advertisement

What the Coding Round Actually Tests

  • Core Java fluency — loops, arrays, String and StringBuilder, collections (HashSet, HashMap, ArrayList).
  • Logic — can you break the problem into steps without an IDE doing it for you?
  • Edge cases — null, empty input, one element, duplicates, negative numbers.
  • Efficiency — can you move from a nested-loop O(n²) solution to an O(n) one?
  • Communication — explaining your approach clearly matters as much as the code.

For SDET roles there's a bonus: interviewers love candidates who also show how they would test their own solution (see Test Your Solution below).

The 6 Patterns Behind Most Interview Programs

Learn these six and you can solve the large majority of questions in this guide. Each example is complete and tested.

Pattern 1 — Running max/min (one pass)

Used for: largest, smallest, second largest, max−min difference. Track the values you need while walking the array once — no sorting.

public static int secondLargest(int[] a) {
    if (a == null || a.length < 2) throw new IllegalArgumentException("Need at least 2 elements");
    int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
    for (int x : a) {
        if (x > first) { second = first; first = x; }
        else if (x > second && x != first) { second = x; }
    }
    if (second == Integer.MIN_VALUE) throw new IllegalArgumentException("No second largest value");
    return second;
}
// secondLargest(new int[]{12, 35, 1, 10, 34, 1}) → 34

Pattern 2 — HashSet for duplicates and uniqueness

Used for: duplicate elements, duplicate characters, unique elements, common elements. HashSet.add() returns false when the value is already present — that single fact turns an O(n²) nested loop into O(n).

public static Set<Integer> findDuplicates(int[] a) {
    Set<Integer> seen = new HashSet<>();
    Set<Integer> duplicates = new LinkedHashSet<>();
    for (int x : a) {
        if (!seen.add(x)) duplicates.add(x);   // add() returns false if already present
    }
    return duplicates;
}
// findDuplicates(new int[]{4, 2, 7, 2, 4, 9, 4}) → [2, 4]

Pattern 3 — HashMap for counting

Used for: character frequency, word frequency, element frequency, first non-repeated character, majority element. merge() keeps the counting code to one line.

public static Map<String, Integer> wordFrequency(String sentence) {
    Map<String, Integer> freq = new LinkedHashMap<>();
    for (String word : sentence.toLowerCase().trim().split("\\s+")) {
        freq.merge(word, 1, Integer::sum);
    }
    return freq;
}
// wordFrequency("the cat and the hat") → {the=2, cat=1, and=1, hat=1}

Pattern 4 — Two pointers

Used for: palindrome check, reversing an array in place, moving zeros, merging sorted arrays. One index starts at each end and they move toward each other.

public static boolean isPalindrome(String s) {
    String t = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
    int i = 0, j = t.length() - 1;
    while (i < j) {
        if (t.charAt(i++) != t.charAt(j--)) return false;
    }
    return true;
}
// isPalindrome("A man, a plan, a canal: Panama") → true

Pattern 5 — Digit extraction with % 10 and / 10

Used for: reverse a number, sum of digits, count digits, palindrome number, Armstrong, strong, neon and spy numbers. n % 10 gives the last digit; n / 10 removes it.

public static int reverse(int n) {
    int rev = 0;
    while (n != 0) {
        rev = rev * 10 + n % 10;   // take the last digit
        n /= 10;                   // drop the last digit
    }
    return rev;
}
// reverse(12345) → 54321   (mention integer overflow for very large inputs)

Pattern 6 — Complement lookup

Used for: pair with a given sum (Two Sum), missing number checks. For each value, ask "have I already seen the number that completes it?"

public static int[] pairWithSum(int[] a, int target) {
    Set<Integer> seen = new HashSet<>();
    for (int x : a) {
        if (seen.contains(target - x)) return new int[]{target - x, x};
        seen.add(x);
    }
    return new int[0];   // no pair found
}
// pairWithSum(new int[]{8, 3, 5, 11}, 16) → [5, 11]

Run and tweak any of these in the Java Online Compiler, or step through them line by line in the Java Code Visualizer.

Complexity Cheat Table

Program Naive approach Better approach
Find duplicates Nested loops — O(n²) HashSet — O(n) time, O(n) space
Second largest Sort — O(n log n) One pass — O(n), O(1) space
Pair with given sum Nested loops — O(n²) HashSet — O(n)
Character / word frequency Count each item separately — O(n²) HashMap — O(n)
Missing number (1 to n) Search for each number — O(n²) Sum formula n(n+1)/2 — O(n), O(1) space
Prime check Divide up to n — O(n) Divide up to √n — O(√n)
Anagram check Sort both — O(n log n) Count characters — O(n)

Check the complexity of your own solutions with the Time & Space Complexity Calculator.

Part 1 — Array Programs

Grouped tutorials (several programs each, with full code):

Most-asked individual programs:

Part 2 — Number Programs

Most-asked individual programs:

Part 3 — String Programs

  • String Basics — reverse, palindrome, compare, vowels/consonants, duplicate and first non-repeated characters.
  • String Advanced (Word-Level) — reverse each word, word order, longest word, word frequency, anagram, sort words.

Most-asked individual programs:

Part 4 — Matrix and 2D Array Programs

Less common, but they appear in service-company coding rounds:

  1. create and print a 2D array ·
  2. transpose 
  3. multiply two matrices
  4. sum of diagonals 
  5. print diagonals
  6. identity matrix 
  7. upper and lower triangular.

Browse every program in the Java Code Snippets category.

How to Answer a Coding Question in the Interview

  1. Repeat the problem and ask one clarifying question — "Can the array contain negatives or duplicates?"
  2. Say the simple approach first, with its complexity: "A nested loop works but is O(n²)."
  3. Improve it using one of the six patterns: "With a HashSet I can do it in one pass, O(n)."
  4. Write clean code with meaningful names — no single-letter variables except loop indexes.
  5. Walk through an example out loud, then the edge cases: null, empty, one element, all equal.
  6. Mention how you'd test it — the step that sets SDET candidates apart.

Test Your Solution — the SDET Bonus

Finishing with a quick test shows the interviewer you think like a tester. Here is a TestNG data-driven test for the secondLargest method above (assuming it lives in a class called JavaPrograms):

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class SecondLargestTest {

    @DataProvider(name = "arrays")
    public Object[][] arrays() {
        return new Object[][] {
            { new int[]{12, 35, 1, 10, 34, 1}, 34 },   // normal case with a duplicate
            { new int[]{5, 5, 4}, 4 },                 // largest value repeated
            { new int[]{-3, -1, -2}, -2 }              // all negative
        };
    }

    @Test(dataProvider = "arrays")
    public void returnsSecondLargest(int[] input, int expected) {
        Assert.assertEquals(JavaPrograms.secondLargest(input), expected);
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void allEqualValuesThrow() {
        JavaPrograms.secondLargest(new int[]{7, 7, 7});
    }
}

Learn more about data providers in TestNG annotations and setup.

A Four-Week Practice Plan

Week Focus Goal
1 Patterns 1 & 5 — array basics and number programs Write 15 programs from memory without an IDE
2 Patterns 2 & 3 — HashSet and HashMap programs Explain O(n²) → O(n) for each one out loud
3 Pattern 4 and string programs Solve 10 string questions in under 10 minutes each
4 Pattern 6, matrix programs and mock rounds Two timed mocks in the Java Interview Simulator

From Real Projects

My automation work has been in Java — Selenium WebDriver with TestNG in Eclipse — so the programs on this page are the kind of logic you end up writing inside real frameworks: reading test data from Excel with Apache POI, looping through rows of a table, comparing expected and actual values. In interviews for automation roles, expect basic Java programs alongside questions on OOP concepts such as method overloading, overriding and constructors. Practice writing them by hand without an IDE, and always say how you'd test your own code with edge cases like empty input or duplicates.

Complete Index of Java Programs

Every program on navtutorial.com, grouped the way interviewers ask them. Each one has the full code, output and the follow-up questions you'll get.

Java Array Programs (43)

Java 2D Array & Matrix Programs (10)

Java Number Programs (41)

Java String Programs (31)

Frequently Asked Questions

What coding questions are commonly asked in automation testing interviews?

Mostly array, number and string programs: reverse a string or array, find duplicates, second largest element, pair with a given sum, prime and palindrome checks, anagrams and character or word frequency.

How do you find the second largest element in an array?

Traverse the array once while tracking the largest and second-largest values (Pattern 1 above). It runs in O(n) without sorting. Remember to handle arrays where every value is the same.

How do you find duplicate elements efficiently?

Use a HashSet. If add() returns false, the element already exists, so the solution runs in O(n) instead of O(n²).

How do you check whether two strings are anagrams?

Either sort both strings and compare them (O(n log n)), or count each character's frequency and compare the counts (O(n)).

Can I use Java 8 streams in a coding interview?

Yes, if you can explain them — but write the loop-based version first. Interviewers mainly want to see your logic, and a stream one-liner can hide it.

How many programs should I practice before an SDET interview?

Quality beats quantity. Master the six patterns and around 30–40 of the most-asked programs so you can write them from memory and explain their complexity.

Do these programs include runnable Java code?

Yes. Every program on this site includes complete Java source code you can copy, compile and run — or paste into the Java Online Compiler.

Keep Learning