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.
What the Coding Round Actually Tests
- Core Java fluency — loops, arrays,
StringandStringBuilder, 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):
- Array Basics & Calculations — initialize, print, sum, average, second largest/smallest, max−min.
- Sort, Reverse, Duplicates & Frequency — bubble sort, reverse, find/remove duplicates, count frequency.
- Rotation, Missing Number, Pair Sum & Majority — rotation, missing number, pair sum, Boyer–Moore voting, move zeros.
Most-asked individual programs:
- second largest
- duplicate elements
- remove duplicates
- reverse an array
- pair with given sum
- missing number 1 to n
- move zeros to end
- majority element
- rotate left
- merge two arrays
- common elements
- element frequency
Part 2 — Number Programs
- Number Basics & Intermediate — even/odd, swap, reverse, factorial, prime, palindrome, Armstrong.
- Number Advanced & Test-Oriented — GCD/LCM, sum of digits, recursion, decimal↔binary, Neon, Fibonacci.
Most-asked individual programs:
- prime number
- palindrome number
- reverse a number
- factorial
- Fibonacci series
- Armstrong number
- swap two numbers
- sum of digits
- GCD / HCF
- decimal to binary
- leap year
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:
- reverse a string
- palindrome string
- anagram
- duplicate characters
- character frequency
- word frequency
- reverse each word
- reverse word order
- Remove whitespaces
- string compression.
Part 4 — Matrix and 2D Array Programs
Less common, but they appear in service-company coding rounds:
- create and print a 2D array ·
- transpose
- multiply two matrices
- sum of diagonals
- print diagonals
- identity matrix
- upper and lower triangular.
Browse every program in the Java Code Snippets category.
How to Answer a Coding Question in the Interview
- Repeat the problem and ask one clarifying question — "Can the array contain negatives or duplicates?"
- Say the simple approach first, with its complexity: "A nested loop works but is O(n²)."
- Improve it using one of the six patterns: "With a HashSet I can do it in one pass, O(n)."
- Write clean code with meaningful names — no single-letter variables except loop indexes.
- Walk through an example out loud, then the edge cases: null, empty, one element, all equal.
- 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)
- How to Declare and Initialize an Array in Java
- Print All Elements of an Array in Java
- How to Find the Length of an Array in Java
- How to Take Array Input From User in Java
- Find Average of Array Elements in Java
- Find Maximum Element in Array in Java
- Find Minimum Element in an Array in Java
- Find Second Largest Element in an Array in Java
- Find Second Smallest Element in an Array in Java
- Find the Difference Between Max and Min in a Java Array
- Sort an Array in Ascending Order in Java
- Sort an Array in Descending Order in Java (3 Practical Methods)
- Reverse an Array in Java (In-Place, Recursive & Stream Methods)
- Find Duplicate Elements in an Array in Java
- Remove Duplicates from an Array in Java
- Count Frequency of Each Element in an Array in Java (HashMap Guide)
- Find Unique Elements in an Array in Java
- Find the First Duplicate Element in a Java Array
- Count Even and Odd Elements in a Java Array
- Separate Even and Odd Elements into Two Arrays in Java
- Count Positive and Negative Numbers in a Java Array (Complete Guide)
- Find Sum of Even and Odd Elements Separately in a Java Array
- Compare Two Arrays for Equality in Java (Arrays.equals() & Beyond)
- Merge Two Arrays in Java (With and Without Sorting)
- Copy One Array to Another in Java (Shallow vs Deep Copy Explained)
- Find Common Elements Between Two Arrays in Java (HashSet Method)
- Find Element at a Specific Index in a Java Array (Beginner Guide)
- Replace an Element at a Specific Index in a Java Array
- Swap Two Elements in a Java Array (Temp Variable & XOR Methods)
- Rotate an Array to the Left in Java
- Rotate an Array to the Right in Java (Reversal Algorithm Guide)
- Find the Index of an Element in a Java Array (Linear & Binary Search)
- Move All Zeros to the End of an Array in Java
- Move All Zeros to the Beginning of an Array in Java
- Move All Negative Numbers to the Beginning of a Java Array
- Find the Missing Number in an Array (1 to n) in Java
- Remove a Specific Element from an Array in Java
- Find a Pair with a Given Sum in a Java Array (Two Sum, O(n) Solution)
- Check if an Array Is Sorted or Not in Java (Ascending & Descending)
- Find the Majority Element in a Java Array (Boyer-Moore Voting)
- Print an Array in Reverse Order Without Reversing It in Java
- Convert an Array to an ArrayList in Java
- Convert an ArrayList to an Array in Java (toArray() Fully Explained)
Java 2D Array & Matrix Programs (10)
- Create and Print a 2D Array in Java (Complete Beginner Guide)
- Find the Sum of All Elements in a 2D Array in Java
- Find the Sum of Each Row in a 2D Array in Java (Step-by-Step)
- Find Sum of Each Column in 2D Array in Java
- Find the Transpose of a Matrix in Java (In-Place & New Matrix Methods)
- Print Diagonal Elements of a Matrix in Java (Both Diagonals)
- Find the Sum of Diagonal Elements of a Matrix in Java (Both Diagonals)
- Multiply Two Matrices in Java (Full Guide With Dimension Rules)
- Check if a Matrix Is an Identity Matrix in Java (Full Guide)
- Display Upper and Lower Triangular Matrix Elements in Java
Java Number Programs (41)
- How to Check Even or Odd Number in Java (5 Easy Methods + Code)
- Check Positive, Negative, or Zero in Java (Code + Interview Answer)
- Swap Two Numbers in Java: With and Without a Third Variable
- Find the Largest Among 3 Numbers in Java (4 Methods + Code)
- Reverse a Number in Java: 4 Methods (Loop, Recursion, StringBuilder)
- Sum of Digits in Java: While Loop, Recursion & Optimized Code
- Count Number of Digits in Java: 4 Methods (Loop, String, Log10)
- Find Factorial of a Number in Java: Loop, Recursion & BigInteger
- Find Power of a Number in Java: Loop, Math.pow() & Recursion
- Check Leap Year in Java: Simple Logic + Full Code
- Check Prime Number in Java: Optimized Code (sqrt(n) Method)
- Check Palindrome Number in Java: Full Code + Logic
- Check Armstrong Number in Java: Full Logic + Code
- Check Perfect Number in Java: Logic, Code & Optimized Method
- Check Strong Number in Java: Logic + Full Code Explained
- Print Fibonacci Series in Java: Loop, Recursion & Memoization
- Sum of Even and Odd Numbers in Java: Array & Range Methods
- Find GCD (HCF) of Two Numbers in Java: Euclidean Algorithm
- Find LCM of Two Numbers in Java: Using GCD (Efficient Method)
- Find Factors of a Number in Java: Brute Force vs Optimized
- Armstrong Numbers in a Range in Java: Efficient Code
- Palindrome Numbers in a Range in Java: Efficient Code
- Sum of First N Natural Numbers in Java: Loop vs Formula
- Check Neon Number in Java: Logic + Full Code Explained
- Reverse a Number Without Loop in Java: Using Recursion
- Print Numbers Without Loop in Java: Recursion (1 to N & N to 1)
- Find Smallest and Largest Digit in a Number in Java
- Convert Decimal to Binary in Java: 4 Methods Explained
- Convert Binary to Decimal in Java: 4 Methods Explained
- Calculate Simple Interest in Java: Formula + Full Code
- Calculate Compound Interest in Java: Formula + Full Code
- Check Happy Number in Java: Logic + Cycle Detection
- Check Harshad Number in Java: Logic + Full Code
- Check Spy Number in Java: Sum vs Product of Digits
- Check Automorphic Number in Java: Logic + Full Code
- Check Magic Number in Java: Digit Sum Reduction
- Check Buzz Number in Java: Divisibility + Last Digit
- Check If a Number Is Binary or Not in Java
- Find Duplicate Numbers in an Array in Java: 4 Methods
- Find Missing Number in a Sequence in Java: 4 Methods
- Verify Number Is Palindrome in Java: A QA Testing Approach
Java String Programs (31)
- Count Digits, Letters, Spaces & Special Chars in Java
- Count Numeric Values in a String in Java: Full Guide
- Extract Numeric Part From a String in Java: 4 Methods
- Validate Number in Range in Java: Inclusive vs Exclusive
- Generate Random Number in Java: Random, Math.random & More
- Compare Two Numeric Values From Strings in Java
- Sum of Numeric Digits in a String in Java: Full Guide
- How to Reverse a String in Java
- Java Palindrome Check
- Compare Strings in Java
- Convert String to Uppercase and Lowercase in Java
- Count Characters in a String Java
- Find String Length Without length() Method in Java
- Concatenate Strings Without + Operator in Java
- Remove Whitespaces from String Java
- Replace Character in String Java
- Check if Strings are Anagrams Java
- Count Digits Letters Spaces Special Characters Java
- Find Duplicate Characters in String Java
- Remove Duplicate Characters from String Java
- Check if String Contains Only Digits Java
- Check if String Contains Only Alphabets Java
- Swap Two Characters in String Java
- Count Words in Sentence Java
- Reverse Each Word in Sentence Java
- Reverse Word Order in Sentence Java
- Find Shortest Word in Sentence Java
- Count Word Frequency in Sentence Java
- Remove Duplicate Words from Sentence Java
- Count Character Frequency in String Java
- Sort Words Alphabetically Java
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
- Java Coding Programs Cheat Sheet — every program on one page
- SDET Coding Interview Questions
- Java Interview Questions for Testers
- The Complete Java for Testers Guide — the concepts behind the code