Java Coding Programs Cheat Sheet
A one-page revision sheet for Java coding rounds in QA, automation and SDET interviews: 70 programs across arrays, numbers and strings, each with the approach and complexity interviewers expect — plus the five patterns behind almost all of them, with tested code. Full explanations and solutions are in Java Coding Programs for Interview.
The 5 Patterns Behind Everything ⭐
| Pattern | Core code | Solves |
|---|---|---|
| Digit extraction | digit = n % 10; n = n / 10; |
Reverse number, palindrome, Armstrong, digit sum |
| Build the reverse | rev = rev * 10 + digit; |
Reverse number, palindrome number |
| Two pointers | i++; j--; until they meet |
Reverse array/string, palindrome string |
| HashSet deduplication | if (!set.add(x)) → duplicate |
Duplicates, first duplicate, pair sum, common elements |
| HashMap frequency | map.merge(key, 1, Integer::sum) |
Character/word frequency, first non-repeated, anagram |
All five in one runnable class
import java.util.*;
public class Patterns {
static int reverse(int n) { // digit extraction + build reverse
int rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return rev;
}
static boolean isPalindrome(String s) { // two pointers
for (int i = 0, j = s.length() - 1; i < j; i++, j--)
if (s.charAt(i) != s.charAt(j))
return false;
return true;
}
static Integer firstDuplicate(int[] a) { // HashSet
Set<Integer> seen = new HashSet<>();
for (int x : a)
if (!seen.add(x))
return x;
return null;
}
static Character firstNonRepeated(String s) { // HashMap frequency
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray())
freq.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : freq.entrySet())
if (e.getValue() == 1)
return e.getKey();
return null;
}
static int secondLargest(int[] a) { // single pass
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) {
second = first;
first = x;
} else if (x > second && x != first) {
second = x;
}
}
return second;
}
public static void main(String[] args) {
System.out.println(reverse(12345)); // 54321
System.out.println(
isPalindrome("madam") + " " +
isPalindrome("java")
); // true false
System.out.println(
firstDuplicate(new int[]{3, 1, 4, 1, 5, 3})
); // 1
System.out.println(firstNonRepeated("swiss")); // w
System.out.println(
secondLargest(new int[]{10, 40, 40, 25})
); // 25
}
}
These outputs are real — the class was compiled and run. Step through it line by line in the Java Code Visualizer.
Array Programs (29)
Basics and calculations
| Program | Approach | Time |
|---|---|---|
| Declare and initialize an array | int[] a = {…} or new int[n] |
— |
| Print elements | Loop or Arrays.toString() |
O(n) |
| Sum of elements | Accumulate in a loop | O(n) |
| Average | Sum, then divide as double |
O(n) |
| Largest / smallest | Single pass tracking max and min | O(n) |
| Second largest ⭐ | Track first and second in one pass (skip equal values) | O(n) |
| Second smallest | Track smallest and second smallest | O(n) |
| Maximum difference | Track the minimum so far; compare each element | O(n) |
Solutions: Array Basics & Calculations
Sorting, reverse and duplicates
| Program | Approach | Time |
|---|---|---|
| Sort ascending | Bubble sort by hand, or Arrays.sort() |
O(n²) / O(n log n) |
| Sort descending | Reverse the comparison, or sort then reverse | O(n²) / O(n log n) |
| Reverse an array | Two-pointer swap | O(n) |
| Find duplicates (brute force) | Nested loops | O(n²) |
| Find duplicates (optimal) ⭐ | HashSet — add() returns false |
O(n) |
| Remove duplicates ⭐ | LinkedHashSet keeps order |
O(n) |
| Count frequency | HashMap counts | O(n) |
| Unique elements | Frequency equals 1 | O(n) |
| First duplicate | First failed HashSet.add() |
O(n) |
Solutions: Array Sorting, Reverse & Duplicates
Rotation, search and patterns
| Program | Approach | Time |
|---|---|---|
| Left rotation | Shift left, append the first element (or reversal trick) | O(n) |
| Right rotation | Shift right, prepend the last element | O(n) |
| Missing number ⭐ | Expected sum n(n+1)/2 − actual sum | O(n) |
| Pair with given sum ⭐ | HashSet complement lookup | O(n) |
| Majority element | Moore's voting algorithm | O(n) |
| Move zeros to the end | Write-index approach | O(n) |
| Count even / odd | % 2 check |
O(n) |
| Count positive / negative | Sign comparison | O(n) |
| Merge two arrays | Copy into a new array (System.arraycopy) |
O(n+m) |
| Common elements | HashSet lookup | O(n+m) |
| Compare arrays | Arrays.equals() or a loop |
O(n) |
| Array ↔ ArrayList | new ArrayList<>(List.of(…)) / toArray() |
O(n) |
Solutions: Array Rotation, Missing Number & Pair Sum
Number Programs (22)
Basics and classics
| Program | Approach |
|---|---|
| Even / odd | n % 2 == 0 |
| Positive / negative | Sign comparison |
| Swap two numbers | Temp variable, or arithmetic swap without one |
| Reverse a number ⭐ | Digit extraction + build reverse |
| Count digits | Divide by 10 in a loop, or String.valueOf(n).length() |
| Factorial | Multiply 1..n (use long or BigInteger for large n) |
| Power | Loop, or Math.pow() |
| Leap year | Divisible by 4, not by 100 unless by 400 |
| Prime ⭐ | Check divisors up to √n |
| Palindrome number ⭐ | Reverse and compare |
| Armstrong number | Sum of digits each raised to the number of digits |
| Perfect number | Sum of proper divisors equals n |
| Strong number | Sum of the factorials of the digits equals n |
| Fibonacci series ⭐ | Two running variables |
Solutions: Reverse, Prime, Palindrome & Armstrong
Advanced
| Program | Approach |
|---|---|
| GCD / LCM ⭐ | Euclidean algorithm; LCM = a × b / GCD |
| Sum of digits | Digit extraction |
| Smallest / largest digit | Track while extracting digits |
| Reverse using recursion | Recursive digit processing |
| Print 1..n recursively | Recursion with a base case |
| Decimal → binary | Divide by 2 repeatedly, or Integer.toBinaryString() |
| Binary → decimal | Multiply the result by 2 and add each bit, or Integer.parseInt(s, 2) |
| Neon number | Sum of the digits of n² equals n |
Solutions: GCD/LCM, Recursion & Number Systems
String Programs (19)
Character level
| Program | Approach |
|---|---|
| Reverse a string ⭐ | StringBuilder.reverse() — and be ready to do it manually with a char array |
| Palindrome check ⭐ | Two pointers, or reverse and compare |
| Compare strings | equals() / equalsIgnoreCase() — never == |
| Count vowels and consonants | Classify each character |
| Count characters | length(), or count excluding spaces |
| Duplicate characters ⭐ | HashMap frequency, count > 1 |
| Remove duplicate characters ⭐ | LinkedHashSet<Character> or a StringBuilder with a seen-set |
| Non-repeated characters | Frequency equals 1 |
| First non-repeated character ⭐ | LinkedHashMap counts, first with count 1 |
| Swap characters | Char array manipulation |
| Digits / letters only | Character.isDigit() / isLetter(), or a regex |
Solutions: Reverse, Palindrome, Vowels & Duplicates
Word level
| Program | Approach |
|---|---|
| Count words | trim().split("\\s+") |
| Reverse each word ⭐ | Split, reverse each with StringBuilder, join |
| Reverse word order | Split and join backwards |
| Longest / shortest word | Track lengths in one pass |
| Word frequency | HashMap counts |
| Anagram check ⭐ | Sort both char arrays, or compare frequency counts |
| Sort words alphabetically | Arrays.sort() |
| Character frequency | merge() or getOrDefault() |
Solutions: Reverse Each Word, Word Frequency & Anagram
⭐ = most frequently asked in interviews.
Coding Round Tips
- Practice writing programs from memory, without an IDE.
- Say the brute-force approach first, then optimize.
- Dry-run with a sample input — including an empty array, one element and duplicates.
- State time and space complexity.
- Avoid the classic slips: integer division in averages,
==instead ofequals()for strings, andintoverflow in factorials.
Practice timed questions in the Java Interview Simulator.
From Real Projects
Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Use it for revision the night before, not as a replacement for writing the programs yourself.
📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation
FAQs
Which Java programs are asked most in SDET interviews?
Reverse a string, palindrome, duplicates in an array or string, second largest, first non-repeated character, anagram, prime, Fibonacci, missing number and pair with a given sum.
Can I use built-in methods like StringBuilder.reverse()?
Usually yes to start — then be ready to do it manually, because interviewers often ask for the logic without library helpers.
How many programs should I practice?
Master the five patterns and the starred programs first (about 20); the rest are variations of the same patterns.
Do automation interviews ask about time complexity?
Often — at least to explain why a HashSet solution (O(n)) beats nested loops (O(n²)).
How should I practice?
Write each program from memory, run it with edge cases, then explain it out loud as if in an interview.