Working with Strings

1. Creating Strings

FormExample
LiteralString s = "hello";
Constructornew String("hi") (avoid)
From char[]new String(chars)
From bytesnew String(bytes, StandardCharsets.UTF_8)
Text block"""multi\nline"""

2. Understanding String Immutability

AspectDetail
Classfinal class String
Mutating method?None — all methods return NEW String
BenefitThread-safe, hashable, cacheable, secure

3. Understanding String Pool

ItemDetail
LocationHeap (since Java 7)
LiteralAuto-interned
new String("x")Allocates new object outside pool
s.intern()Returns canonical pool reference

4. Concatenating Strings

MethodUse
+ operatorCompiles to StringBuilder (Java 9+ uses invokedynamic)
String.concat(s)Single concat
String.join(delim, parts)With separator
StringBuilderLoops/many concats
"%s".formatted(x)Templated

5. Comparing Strings

MethodUse
a.equals(b)Value equality
a.equalsIgnoreCase(b)Case-insensitive
a.compareTo(b)Lexicographic, <0 / 0 / >0
a.compareToIgnoreCase(b)Case-insensitive ordering
a == bReference identity — avoid
Null-safeObjects.equals(a, b)

6. Extracting Substrings

MethodDescription
substring(start)From index to end
substring(start, end)End exclusive
charAt(i)Single char
chars()IntStream of code points
codePoints()Unicode-aware stream

7. Searching Strings

MethodReturns
contains(seq)boolean
indexOf(s) / lastIndexOf(s)int (-1 if absent)
startsWith(p) / endsWith(p)boolean
matches(regex)Full match

8. Modifying Strings

MethodResult
replace(c, c)Replace all chars
replace(seq, seq)Literal replacement
replaceAll(regex, repl)Regex replacement
replaceFirst(regex, repl)Only first match
strip() / trim()Whitespace removal (strip is Unicode-aware, Java 11+)
stripLeading() / stripTrailing()Side-specific

9. Splitting Strings

MethodUse
split(regex)All splits
split(regex, limit)Limit elements
Pattern.compile(re).split(s)Reuse compiled pattern
Warning: split uses regex — escape special chars (e.g. "\\." for dot).

10. Formatting Strings

FormExample
String.format(fmt, args)String.format("%-10s %5d", "x", 42)
"fmt".formatted(args)Java 15+
%s %d %f %x %b %c %nType specifiers
%5.2fWidth.precision
%-10sLeft-align
%,dThousands separator

11. Converting Cases

MethodNotes
toLowerCase()Uses default Locale
toLowerCase(Locale.ROOT)Locale-independent (recommended)
toUpperCase(Locale)Locale-aware
Note: "i".toUpperCase(Locale.forLanguageTag("tr")) = "İ" (Turkish dotted I).

12. Using StringBuilder

Example: StringBuilder

StringBuilder sb = new StringBuilder();
sb.append("Hello").append(", ").append(name);
sb.insert(0, ">> ").reverse().deleteCharAt(0);
String result = sb.toString();
MethodEffect
appendAdd to end
insert(i, x)Insert at index
delete(start, end)Remove range
reverseIn-place reverse
setLength(n)Truncate or pad
capacity() / ensureCapacity(n)Internal buffer

13. Using StringBuffer

AspectStringBufferStringBuilder
Thread-safeYes (synchronized)No
SpeedSlowerFaster
When to useMulti-thread mutation (rare)Default choice

14. Working with Text Blocks JAVA 15+

Example: Text block

String json = """
        {
            "name": "Alice",
            "age": 30
        }
        """;
String html = """
        <div class="msg">
            Hello, %s!
        </div>""".formatted(name);
RuleDetail
DelimiterTriple double-quotes """
First lineMust be empty after opening """
IndentationStripped to align with closing """
Escapes\ (line continuation), \s (significant space)