How to learn Strings
A Java String is an immutable sequence of UTF-16 code units. Operations such as toUpperCase, replace, and substring return a value; they do not edit the original object. Immutability makes strings safe to share, but repeated concatenation in a loop can allocate many temporary objects.
Decide whether a task works with char values, Unicode code points, or whole words. A char is sufficient for many introductory ASCII exercises, but it cannot represent every Unicode character by itself. That distinction matters in production text processing even when a practice input is simple.
Recommended learning order
- Inspect without changing: Practice length, charAt, indexOf, contains, startsWith, and substring while checking bounds.
- Compare content: Use equals or equalsIgnoreCase for content and understand why == only answers whether two references identify the same object.
- Build efficiently: Use StringBuilder when appending or editing repeatedly, then convert to String at the boundary.
- Recognize text patterns: Move to frequency counts, two pointers, sliding windows, and normalization only after basic methods are predictable.
Tested example: Normalize and test a palindrome
The method builds a lowercase alphanumeric representation once, then compares mirrored characters. The definition is explicit: punctuation and letter case do not affect the result.
public class Main {
static boolean isPalindrome(String text) {
StringBuilder clean = new StringBuilder();
for (char ch : text.toCharArray()) {
if (Character.isLetterOrDigit(ch)) {
clean.append(Character.toLowerCase(ch));
}
}
for (int left = 0, right = clean.length() - 1; left < right; left++, right--) {
if (clean.charAt(left) != clean.charAt(right)) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("Never odd or even"));
}
}Expected output
trueCommon mistakes
- Comparing text with == instead of equals, producing results that depend on object identity and string interning.
- Ignoring the returned value of trim, replace, or toUpperCase because Strings cannot be modified in place.
- Appending with + inside a large loop when one StringBuilder would avoid repeated copying.
- Calling a method on a possibly null reference instead of defining whether null is invalid or has a special meaning.
How to practice
Start with inspection and transformation methods, then reverse and palindrome tasks, and finally frequency maps and window problems. For every comparison exercise, test empty text, one character, mixed case, and repeated characters.
Exercises to do first
- Extract a substring — Practice inclusive start and exclusive end indices.
- Reverse a string — Compare a manual two-pointer solution with StringBuilder.reverse().
- Palindrome string — Write down the normalization rules before comparing characters.