Copy, paste, and use these battle-tested utilities for your programs
String manipulation shows up everywhere in APCS-A: trimming whitespace, splitting text, checking patterns, and more. Rather than retyping string logic every time, copy these proven methods and use them in your projects.
TemplateDriver.java. This is your "home" for testing—you'll make modest modifications but mostly just paste the methods you want to test into it.
Browse the utilities below. Click on each one to reveal the code, then copy what you need.
Purpose: Remove all consecutive multiple spaces from a string, reducing them to single spaces, and trim leading/trailing whitespace
Example: removeMultipleSpaces("Hello World") returns "Hello World"
Example: removeMultipleSpaces(" Java rocks! ") returns "Java rocks!"
When to Use: Data cleanup, parsing user input, normalizing whitespace in log files, text preprocessing, file parsing
// Clean up user input from a form
String userInput = " Hello World ";
String cleaned = removeMultipleSpaces(userInput);
System.out.println("'" + cleaned + "'"); // Output: 'Hello World'
// Parse data from a log file with inconsistent spacing
String logEntry = "INFO - User logged in successfully";
String normalized = removeMultipleSpaces(logEntry);
System.out.println(normalized); // INFO - User logged in successfully
// Clean CSV data before splitting
String csvLine = "John , Doe , Computer Science";
String[] parts = removeMultipleSpaces(csvLine).split(",");
for(String part : parts) {
System.out.println(part.trim()); // Additional trim() for column whitespace
}
// Alternative for advanced students: One-pass regex approach
// String result = str.trim().replaceAll(" +", " ");
// But the loop approach teaches iterative problem-solving!
Regex Alternative (Advanced): Students familiar with regular expressions can achieve the same result in a single pass: str.trim().replaceAll(" +", " "). The pattern " +" means "one or more spaces," and replaceAll() replaces all matching sequences with a single space. This is more elegant and efficient—no loop needed! However, the iterative approach taught here is valuable because it reinforces the concept of repeated operations and loop termination conditions. Both are correct; choose based on readability and whether you want to emphasize iteration or regex.
Purpose: Remove all consecutive multiple spaces using recursion instead of iteration. This version demonstrates how recursion can solve the same problem as the loop-based approach — a classic teaching moment for understanding different algorithmic approaches.
Example: removeMultipleSpacesRecursively("Hello World") returns "Hello World"
Example: removeMultipleSpacesRecursively(" Java rocks! ") returns "Java rocks!"
When to Use: Learning recursion, understanding base case + recursive case, comparing iteration vs. recursion approaches, interview prep, call stack visualization
Purpose: Returns the hexadecimal memory address of any object, formatted as "@" followed by the hex address. This demonstrates that every object in Java inherits from the Object class and has a unique memory location.
Example: String s1 = "Hello"; String s2 = new String("Hello");
Both contain the same text, but obtainAddress(s1) and obtainAddress(s2) return different memory addresses because they're different objects in memory.
When to Use: Debugging reference types, distinguishing object identity from equality, understanding memory layouts, learning polymorphism, verifying that two variables point to the same object vs. different objects with same content
System.identityHashCode(obj) gets the integer identity hash code from any objectInteger.toHexString(x) converts that integer to hexadecimal (base 16)@556e0e67 that represents the object's memory addressObject obj — the most general typeString s = "Hello";
Integer i = 42;
ArrayList<String> list = new ArrayList<>();
Object plain = new Object();
System.out.println(obtainAddress(s)); // e.g., @556e0e67
System.out.println(obtainAddress(i)); // e.g., @3a5c0e43
System.out.println(obtainAddress(list)); // e.g., @12b3d8c9
System.out.println(obtainAddress(plain)); // e.g., @7c30a502
// Same method, different object types! That's polymorphism in action.
Identity vs. Equality (Why This Matters)
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); // true (same content)
System.out.println(s1 == s2); // false (different objects in memory!)
System.out.println(obtainAddress(s1)); // e.g., @556e0e67
System.out.println(obtainAddress(s2)); // e.g., @3a5c0e43 (DIFFERENT address!)
// Same content (".equals()"), different identity (".obtainAddress()"),
// different memory locations ("==").
// This is a crucial distinction in Java!
How It Relates to obtainAddressViaObjectClass() (Comparison)
super keywordObject obj (any object, since all classes inherit from Object)Purpose: Returns the object address by directly calling Object.toString() via the super keyword. This demonstrates how to access the parent class's (Object's) default implementation when your class inherits directly from Object.
Important: This method takes NO parameters and must be called FROM WITHIN a class that directly extends Object (or doesn't explicitly extend anything, since all classes implicitly extend Object by default).
When to Use: Learning the super keyword, understanding inheritance chains, calling parent class methods, exploring Object class behavior, verifying what the default toString() looks like
public String getAddress() { return obtainAddressViaObjectClass(); }public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getAddressViaObjectClass() {
// This calls Object's toString() method directly via super
return obtainAddressViaObjectClass();
}
// If you DON'T override toString(), the default Object version is used:
// Result: Student@7c30a502
// If you DO override toString():
@Override
public String toString() {
return "Student: " + name;
// Result: Student: Alice
}
}
// Usage:
Student s = new Student("Alice");
System.out.println(s.toString()); // Student: Alice (overridden version)
System.out.println(s.getAddressViaObjectClass()); // Student@7c30a502 (Object's default)
Comparison: obtainAddress() vs. obtainAddressViaObjectClass() (Critical Difference!)
Purpose: Extracts and returns the last character of a string as a String object (not a char primitive). This demonstrates a design decision: should utility methods return primitive types (char) or object types (String)?
Example: lastSymbol("Hello") returns "o" (as a String)
Example: lastSymbol("Java") returns "a" (as a String)
When to Use: String manipulation chains, text processing, working in contexts where you need String objects, maintaining type consistency in string utility methods
int len = str.length(); — Find how many characters are in the string. For "Hello", len = 5.char lastChar = str.charAt(len-1); — Strings are 0-indexed, so the last character is at index (length - 1). For "Hello", that's index 4, which is 'o'.String.valueOf(lastChar) — Convert the char primitive to a String object using String.valueOf(). This wraps 'o' as "o".lastSymbol("hello").toUpperCase() returns "O". With char, you can't chain String methods.lastSymbol(str).toUpperCase().lastSymbol(String str) (returns String) for the utility belt.lastCharacter(String str) (returns char) for cases where primitive efficiency matters.lastSymbol("") will throw StringIndexOutOfBoundsException (index -1 is invalid). Add a guard clause if defensive coding is needed: if (str.length() == 0) return "";lastSymbol("A") returns "A". Works fine.lastSymbol("hello!") returns "!" as a String. No problem.lastSymbol("café") returns "é".Purpose: Creates a new String by repeating a single character a specified number of times. Useful for generating patterns, decorative lines, or filling strings with repeated characters.
Example: charString('*', 5) returns "*****"
Example: charString('-', 10) returns "----------"
Example: charString('=', 20) returns "==================== (useful for section dividers)
When to Use: Creating formatted output, drawing ASCII art, generating divider lines, padding strings, creating visual separators in text-based interfaces
String temp = ""; — Create an empty string to build the result.for(int i = 1; i <= len; i++) — Iterate from 1 to len (inclusive), adding the character each time.temp += c; — Append the character c to temp on each iteration.temp += c, which is shorthand for temp = temp + c. This creates a new String object each time (Strings are immutable in Java).StringBuilder sb = new StringBuilder(); for(int i = 0; i < len; i++) sb.append(c); return sb.toString();charString('*', 0) returns "" (empty string). The loop doesn't execute.charString('A', 1) returns "A". The loop runs once.charString('!', 3) returns "!!!". Works with any char.charString('é', 4) returns "éééé". Works with Unicode characters.charString('*', -5) returns "" (empty). The loop condition (i <= len) is false from the start.Purpose: Creates a new String by repeating an entire phrase (or string) a specified number of times with no spaces between repetitions. Similar to charString(), but for multi-character strings instead of single characters.
Example: repeatedPhrase("Ha", 3) returns "HaHaHa"
Example: repeatedPhrase("Go!", 4) returns "Go!Go!Go!Go!"
Example: repeatedPhrase("*-", 5) returns "*-*-*-*-*-"
When to Use: Creating patterns, generating decorative output, repeating messages, building formatted strings, creating visual patterns in text-based displays
String temp = ""; — Create an empty string to build the result.for(int i = 1; i <= n; i++) — Iterate from 1 to n (inclusive), adding the phrase each time.temp += x; — Append the entire phrase x to temp on each iteration.repeatedPhrase(String.valueOf(c), len). This is code reuse through generalization.repeatedPhrase("Hello", 0) returns "" (empty string). The loop doesn't execute.repeatedPhrase("Hello", 1) returns "Hello". The loop runs once.repeatedPhrase("", 5) returns "" (empty). Adding empty strings produces empty string.repeatedPhrase("Go ", 3) returns "Go Go Go ". Spaces in x are preserved.repeatedPhrase("*-", 4) returns "*-*-*-*-". Works with any phrase length.repeatedPhrase("Hi", -3) returns "" (empty). The loop condition is false from the start.Purpose: Tests whether a single character (wrapped as a String) is a special symbol—neither a letter, digit, nor whitespace. This is a predicate method that returns a boolean value. It demonstrates how to use Java's built-in Character wrapper class methods for robust character classification.
Example: isSpecialSymbol("@") returns true
Example: isSpecialSymbol("a") returns false
When to Use: String validation, filtering special characters, input sanitization, text processing where you need to distinguish between letters, digits, symbols, and whitespace
if (symbol == null || symbol.length() != 1) return false; — Check that the input is not null and is exactly one character. Single-character strings are what we test.char c = symbol.charAt(0); — Get the single character from the String.!Character.isLetter(c) && !Character.isDigit(c) && !Character.isWhitespace(c) — Use Java's built-in Character class methods to test what the character IS, then negate all three. If it's NOT a letter AND NOT a digit AND NOT whitespace, it must be a special symbol.Character.isLetter(), Character.isDigit(), and Character.isWhitespace() for a reason. These methods handle Unicode correctly and are maintained by the Java library. When you have a standard tool, use it.".,:;'\"!?-@#$%^&*" is incomplete and ASCII-only. It won't handle emoji, accented characters, or other Unicode symbols.isSpecialSymbol(null) returns false (safe; doesn't crash).isSpecialSymbol("") returns false (length check catches this).isSpecialSymbol("@@") returns false (only single characters are tested; length check catches this).isSpecialSymbol(" ") returns false (whitespace is NOT a special symbol).isSpecialSymbol("é") returns false (it's a letter according to Character.isLetter()).isSpecialSymbol("!"), isSpecialSymbol("@"), isSpecialSymbol("#") all return true.String symbol keeps everything in the String domain, not the Unicode code-point domain.String symbol and immediately understand: "I pass a character wrapped as a String." If the parameter were int u (Unicode code point), they'd need to understand casting and code points—unnecessary complexity for a simple test.Purpose: Removes all special symbols from a string, keeping only letters, digits, and whitespace. This method demonstrates composition: it uses isSpecialSymbol() as a helper method to build a more complex operation. This is good design: simple predicates combine into higher-level utilities.
Example: removeSpecialSymbols("Hello@World!") returns "HelloWorld"
Example: removeSpecialSymbols("Price: $9.99") returns "Price 999"
When to Use: Input validation, cleaning user input, removing punctuation or special characters from text, preparing data for further processing
String temp = ""; — Create an empty string to build the result.int len = x.length(); — Determine how many characters we need to process.for(int i = 0; i < len; i++) — Iterate through each character in the input string.String ch = String.valueOf(x.charAt(i)); — Get the current character, then wrap it as a String.if(!isSpecialSymbol(ch)) temp += ch; — Use the isSpecialSymbol() helper method to test the character. If it's NOT a special symbol (i.e., it's a letter, digit, or whitespace), add it to the result.isSpecialSymbol(). We didn't repeat the character-classification logic here; we reused it. This is composability—combining simple methods to build more complex operations.isSpecialSymbol() handles "is this character a special symbol?" while removeSpecialSymbols() handles "iterate and filter." Each method has one job. This makes code easier to understand, test, and maintain.isSpecialSymbol() in other contexts (e.g., string validation, counting special symbols). By keeping them separate, you maximize reusability. This is a core principle of utility design.temp += ch, which works fine for APCS-A. For production code with very large strings, StringBuilder is more efficient. But for learning purposes, the loop-based approach is clearer and more readable.isSpecialSymbol() for each character test. This is intentional composition.removeSpecialSymbols("") returns "" (loop doesn't execute).removeSpecialSymbols("HelloWorld") returns "HelloWorld" (unchanged).removeSpecialSymbols("@#$%") returns "" (all removed).removeSpecialSymbols("Hello@World!") returns "HelloWorld" (spaces removed if they were special; whitespace IS preserved).removeSpecialSymbols("Price: $$$9.99") returns "Price 999" (all symbols removed in one pass).removeSpecialSymbols("user@email.com") returns "useremailcom" (@ and . removed).removeSpecialSymbols() calls isSpecialSymbol() for each character. It's a consumer of the predicate.isSpecialSymbol() as a helper, we avoid duplicating the character-classification logic. If you need to change what counts as "special," you only update isSpecialSymbol().isSpecialSymbol() is a reusable building block (you might use it for validation, counting, categorizing). removeSpecialSymbols() is a convenience wrapper for the specific task of filtering. Having both makes the utility belt more flexible.isSpecialSymbol() when you need to test a single character.removeSpecialSymbols() when you need to strip all special symbols from a string in one go.isSpecialSymbol() to validate user input character-by-character, or use removeSpecialSymbols() to clean entire fields at once.Purpose: Sorts all characters in a string in ascending order by their Unicode numeric values. This arranges letters alphabetically (with uppercase before lowercase), plus digits, symbols, and special characters sorted by their Unicode value. This is a natural and predictable sorting that follows Unicode standards.
Example: alphabetize("hello") returns "ehllo"
Example: alphabetize("Hello@123World") returns "@123HWdelllloor"
When to Use: String analysis, finding repeated characters, sorting user input, text processing, preparing data for analysis where character order matters
char[] chars = x.toCharArray(); — Convert the immutable String to a mutable char array. Strings can't be modified in place; arrays can.Arrays.sort(chars); — Use Java's built-in sort (TimSort, an optimized algorithm). Sorts chars by their Unicode numeric values in ascending order.new String(chars); — Convert the sorted char array back to a String.alphabetize("Hello@123World") →
import java.util.Arrays; for Arrays.sort()alphabetize("") returns "" (toCharArray returns empty array, sort does nothing). No crash.alphabetize("x") returns "x" (single-element array is already sorted). No change needed.alphabetize("abc") returns "abc" (sort detects already-sorted input, O(n) efficiency). Correct.alphabetize("zyx") returns "xyz" (sort rearranges). Correct.alphabetize("aaa") returns "aaa" (sort preserves duplicates). Correct.alphabetize("AaBbCc") returns "ABCabc" (uppercase 65–90 sort before lowercase 97–122). Expected behavior, Unicode order.alphabetize("hello@world.com") returns ".@acdehlllmoorw" (special chars sort by Unicode value first, then letters). Predictable.alphabetize("café") sorts naturally (c, a, f sorted, then é by its Unicode value 233). Works correctly without special handling.Purpose: Reverses a string with optional preservation of casing patterns and punctuation positions. Useful for word-play, simple encryption, and creative text manipulation. The preservation flags allow flexible control over what gets reversed and what stays in place.
Example: reverse("Hello", true, false) returns "OlleH" (case preserved at position 0)
Example: reverse("shouldn't", true, true) returns "t'ndluoh's" (letters reversed, apostrophe stays in position, case preserved)
When to Use: Word-play puzzles, simple text encryption, linguistic exploration, creative writing tools, testing case/punctuation handling logic
import java.util.Collections; and import java.util.ArrayList;reverse("", false, false) → "" (nothing to reverse)reverse("A", true, false) → "A" (reverses to itself, case preserved)reverse("@#$", false, true) → "@#$" (no reversible characters, stays same)reverse("Hello!", true, true) → "!Olleh" (case at position 0 preserved; 'o' becomes 'O'; exclamation at end)reverse("HELLO", true, false) → "OLLEH" (all positions are uppercase, so all reversed chars become uppercase)reverse("123-456", true, true) → "654-321" (digits treated as reversible, hyphen stays, case pattern applied to reversibles)reverse("hello world", false, true) → "dlrow olleh" (space at position 5 preserved as fixed)reverse("HeLLo", false, false) → "olLeH" (straightforward character reversal, case goes with chars)Purpose: Reverses each space-separated word in a phrase while maintaining case and punctuation patterns on each individual word. A convenience wrapper around reverse() that demonstrates method composition and reusability.
Example: reverseWordsInPhrase("hello world") returns "olleh dlrow"
Example: reverseWordsInPhrase("Yes, I'll be there!") returns "Sey, l'li eb ereth!" (each word reversed independently with case/punctuation preserved)
When to Use: Word-play puzzles, creative writing, obfuscation, linguistic exploration, testing phrase-level transformations
String.split(" ") to break the phrase into words at space boundaries.reverse(word, true, true) on each (always preserving case and punctuation on that word).String.join(" ", words) to reconstruct the phrase with reversed words and spaces preserved.reverseWordsInPhrase("") → "" (nothing to split/reverse)reverseWordsInPhrase("hello") → "olleh" (one word, reversed)reverseWordsInPhrase("hello world") → "olleh dlrow" (split preserves empty strings, join reconstructs them)reverseWordsInPhrase(" hello") → " olleh" (leading space creates empty first word)reverseWordsInPhrase("@#$") → "@#$" (no reversible chars in that word, stays same)reverseWordsInPhrase("Hello World") → "OlleH DlroW" (case preserved per word)reverseWordsInPhrase("abc123 456def") → "321cba fed654" (digits are reversible)reverseWordsInPhrase("café Paris") → "éfac siraP" (accents preserved)All 17 string utilities — ready to use in your projects.
TNTStringManip.java, logically organized and searchable
Methods: 17 utilities
Contains: All string manipulation methods, logically organized and searchable
Coverage: Whitespace handling, character classification, repetition, reversal, and phrase operations
1. Download TNTStringManip.java
2. Save it in your project's source folder
3. Call methods statically: TNTStringManip.reverse(...)
4. Reference JavaDoc comments for each method's behavior