Advanced Java string programs for SDET
Java String Programs: Reverse Each Word, Word Frequency & Anagram
Word-level string programs are a favorite in SDET coding rounds: reverse each word, reverse the word order, count words, find word frequency, check anagrams. They're simple to get working and easy to get subtly wrong — extra spaces, capital letters, punctuation and empty input are where interviewers probe. Every program here was compiled and run; the outputs are real.
The One Line That Prevents Most Bugs
String[] words = s.trim().split("\\s+");
split(" ") breaks on every single space, so "I love" produces empty strings between the words. trim() removes leading and trailing spaces, and \\s+ splits on any run of whitespace (spaces, tabs, newlines). Use this line in every word program below.
1. Reverse Each Word ⭐
static String reverseEachWord(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder out = new StringBuilder();
for (String w : words) out.append(new StringBuilder(w).reverse()).append(' ');
return out.toString().trim();
}
// "I love Java programming" → "I evol avaJ gnimmargorp"
Each word's characters are reversed; the word order stays. Build the result with a StringBuilder — concatenating with += in a loop creates a new String every iteration.
2. Reverse the Word Order
static String reverseWordOrder(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder out = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) out.append(words[i]).append(' ');
return out.toString().trim();
}
// "I love Java " → "Java love I" (extra spaces handled)
// Shorter, with the Collections API
List<String> words = Arrays.asList(s.trim().split("\\s+"));
Collections.reverse(words);
String.join(" ", words); // "Selenium with Java" → "Java with Selenium"
Reverse each word vs reverse word order: the first changes characters inside words; the second changes the positions of words.
3. Count Words
static int countWords(String s) {
return s == null || s.isBlank() ? 0 : s.trim().split("\\s+").length;
}
// " Java is fun " → 3, " " → 0
The guard matters: "".trim().split("\\s+").length is 1, not 0 — splitting an empty string returns an array containing one empty string.
4. Longest and Shortest Word
static String longestWord(String s) {
String longest = "";
for (String w : s.trim().split("\\s+"))
if (w.length() > longest.length()) longest = w; // strict > keeps the first on ties
return longest;
}
static String shortestWord(String s) {
String[] words = s.trim().split("\\s+");
String shortest = words[0]; // start from a real word, not ""
for (String w : words) if (w.length() < shortest.length()) shortest = w;
return shortest;
}
// "I love Java programming language" → longest "programming", shortest "I"
Interview follow-up: "what about ties?" — say which one you return (the first, here), or collect all words of the maximum length into a list.
5. Word Frequency ⭐
static Map<String, Integer> wordFrequency(String s) {
Map<String, Integer> freq = new LinkedHashMap<>(); // keeps first-seen order
for (String w : s.toLowerCase().replaceAll("[^a-z0-9\\s]", "").trim().split("\\s+"))
freq.put(w, freq.getOrDefault(w, 0) + 1);
return freq;
}
// "Java is easy, and Java is powerful." → {java=2, is=2, easy=1, and=1, powerful=1}
Lower-casing makes "Java" and "java" the same word; removing punctuation stops "easy," and "easy" counting separately. Use HashMap if order doesn't matter, TreeMap for alphabetical order.
// Java 8 streams version
Map<String, Long> freq = Arrays.stream(s.toLowerCase().trim().split("\\s+"))
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
// "to be or not to be" → {to=2, be=2, or=1, not=1}
6. Anagram Check ⭐
Two strings are anagrams if they contain exactly the same characters with the same counts, in any order — "Listen" and "Silent", "Dormitory" and "Dirty room".
Approach 1 — sort and compare, O(n log n)
static String normalise(String s) {
return s.replaceAll("\\s", "").toLowerCase();
}
static boolean isAnagramSort(String a, String b) {
char[] x = normalise(a).toCharArray(), y = normalise(b).toCharArray();
if (x.length != y.length) return false;
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
// ("Listen","Silent") → true, ("Dormitory","Dirty room") → true, ("abc","abd") → false
Approach 2 — count characters, O(n)
static boolean isAnagramCount(String a, String b) {
String x = normalise(a), y = normalise(b);
if (x.length() != y.length()) return false;
Map<Character, Integer> count = new HashMap<>();
for (char c : x.toCharArray()) count.merge(c, 1, Integer::sum);
for (char c : y.toCharArray()) {
Integer n = count.get(c);
if (n == null || n == 0) return false;
count.put(c, n - 1);
}
return true;
}
// ("aab","abb") → false — same letters, different counts
The "aab"/"abb" case is the one that catches solutions which only check that each letter appears in both strings.
7. Sort Words Alphabetically
String[] w = "banana apple Cherry".split(" ");
Arrays.sort(w); // [Cherry, apple, banana] ⚠️ uppercase sorts first
Arrays.sort(w, String.CASE_INSENSITIVE_ORDER); // [apple, banana, Cherry]
Plain Arrays.sort compares Unicode values, so every capital letter comes before every lowercase letter. Use String.CASE_INSENSITIVE_ORDER — or lower-case the words first if the output can be lowercase.
8. Character Frequency and First Non-Repeated Character
static Map<Character, Integer> charFrequency(String s) {
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) if (c != ' ') freq.merge(c, 1, Integer::sum);
return freq;
}
// "testing" → {t=2, e=1, s=1, i=1, n=1, g=1}
static Character firstNonRepeated(String s) {
for (Map.Entry<Character, Integer> e : charFrequency(s).entrySet())
if (e.getValue() == 1) return e.getKey();
return null; // no unique character
}
// "swiss" → 'w', "aabb" → null
LinkedHashMap is essential for "first non-repeated": it keeps characters in the order they first appeared, so the first entry with count 1 is the answer.
9. Capitalize Each Word
static String capitalizeEachWord(String s) {
return Arrays.stream(s.trim().split("\\s+"))
.map(w -> Character.toUpperCase(w.charAt(0)) + w.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
}
// "selenium WEBDRIVER tutorial" → "Selenium Webdriver Tutorial"
Where Testers Use These
- Comparing UI text — normalizing spaces and case before asserting.
- Validating search and sorting — checking a result list is sorted, case-insensitively.
- Log and report analysis — counting error types by frequency.
- Test data — generating or cleaning names and messages.
10. Remove Duplicate Words, Change Case and Compress a String
static String removeDuplicateWords(String sentence) { // keeps first occurrence, ignores case
Set<String> seen = new LinkedHashSet<>();
StringJoiner out = new StringJoiner(" ");
for (String w : sentence.trim().split("\\s+")) if (seen.add(w.toLowerCase())) out.add(w);
return out.toString();
}
static String toggleCase(String s) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray())
sb.append(Character.isUpperCase(ch) ? Character.toLowerCase(ch) : Character.toUpperCase(ch));
return sb.toString();
}
static String compress(String s) { // run-length encoding
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
int j = i;
while (j < s.length() && s.charAt(j) == s.charAt(i)) j++;
sb.append(s.charAt(i)).append(j - i);
i = j;
}
return sb.length() < s.length() ? sb.toString() : s; // only if it's actually shorter
}
removeDuplicateWords("Test the the test Login") → Test the Login
toggleCase("Java 21") → jAVA 21, "Java".toUpperCase() → JAVA
compress("aaabbcccc") → a3b2c4, compress("abc") → abc
- Duplicate words: a
LinkedHashSetkeeps the first occurrence in order; lower-casing the key makes "Test" and "test" duplicates. Decide with the interviewer whether case should matter. - Case:
toUpperCase()/toLowerCase()for the whole string;Character.isUpperCasefor toggling. In tests, compare withequalsIgnoreCaserather than converting both sides. - Run-length compression: count each run of the same character. Return the original when the "compressed" version isn't shorter — "abc" would become "a1b1c1".
The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.
Complexity
| Program | Time |
|---|---|
| Reverse words, count, longest/shortest, frequency, char frequency | O(n) |
| Anagram by sorting, sort words | O(n log n) |
| Anagram by counting | O(n) |
Step through any of these line by line — watching the StringBuilder and the map fill up — in the Java Code Visualizer.
From the Interview Room
My automation work has been in Java — Selenium WebDriver scripts with TestNG in Eclipse — and I use OOP concepts such as classes and objects, method overloading, overriding and constructors in page classes and utilities. Small programs like this one are the building blocks of real framework code: looping through data, comparing expected and actual values, and handling edge cases. 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. Normalize case and spacing before comparing words.
📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation
Frequently Asked Questions
How do you reverse each word in a string in Java?
Split with trim().split("\\s+"), reverse each word with new StringBuilder(word).reverse(), and join them with spaces.
Reverse each word vs reverse word order?
Reversing each word changes the characters inside words ("Java" → "avaJ"); reversing word order changes the words' positions ("I love Java" → "Java love I").
Why use split("\s+") instead of split(" ")?
It handles multiple spaces, tabs and newlines; split(" ") produces empty strings between consecutive spaces.
How do you count word frequency?
Lower-case the text, remove punctuation, split into words, and count with map.getOrDefault(word, 0) + 1 or Collectors.groupingBy.
What's the fastest way to check anagrams?
Counting characters is O(n); sorting both strings is O(n log n) but shorter to write. Normalize case and spaces first either way.
How do you sort words ignoring case?
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER) — plain Arrays.sort puts all capitalized words first.