Strings & StringBuilder
String methods, immutability, comparison, formatting, text blocks and fast building with StringBuilder.
Text is everywhere: names, messages, JSON, log lines, user input. In Java, text is represented by the String class. This lesson covers the methods you will use every day, the rules that trip people up (immutability and comparison), formatting, text blocks, and StringBuilder for building strings efficiently.
Creating strings#
Special characters use escape sequences:
Essential String methods#
Remember: substring(begin, end) includes begin but excludes end. And charAt or substring with an index outside the string throws StringIndexOutOfBoundsException.
strip()(Java 11) understands all Unicode whitespace; the oldertrim()removes only ASCII spaces and control characters. Preferstrip(),stripLeading()andstripTrailing()in modern code.
Strings are immutable#
Once created, a String object never changes. Methods that seem to modify it actually return a new string:
Immutability makes strings safe to share between different parts of a program (and between threads), and lets Java cache and reuse them.
Comparing strings#
Java keeps string literals in a shared string pool, so identical literals can be the same object, which is why a == b happens to be true. Never rely on that: strings built at runtime (user input, concatenation, file contents) are separate objects. Always compare contents with equals.
compareTo returns a negative number, zero, or a positive number depending on alphabetical (Unicode) order. It is what sorting uses.
Splitting and joining#
The argument to split is a regular expression. Characters like . and | have special meanings, so to split on a literal dot write split("\\.").
Working with characters#
Formatting strings#
String.format (or the equivalent instance method formatted, Java 15+) builds text from a template:
Text blocks (Java 15+)#
For multi-line text such as JSON, SQL or HTML, use a text block delimited by triple quotes:
The opening """ must be followed by a newline. Java removes the common indentation (based on the least-indented line, including the closing """), so you can indent the block naturally with your code. No escaping of " is needed inside.
StringBuilder: building strings efficiently#
Because strings are immutable, s += "x" inside a loop creates a new string on every pass and copies all previous characters. For 100,000 iterations that is a lot of wasted work. StringBuilder is a mutable sequence of characters designed for building text:
Most StringBuilder methods return the builder itself, so calls can be chained. Call toString() when you need a real String.
When should you use it?
- Inside loops that build up text: yes, use
StringBuilder. - A single expression like
"Hi " + name + "!": plain+is fine; the compiler optimises it. StringBufferis an older, synchronised (thread-safe but slower) version. You rarely need it.
Useful conversions#
Integer.parseInt("12a") throws a NumberFormatException; you will learn to handle that in the exceptions lesson.
Common mistakes#
- Comparing strings with
==instead ofequals. - Ignoring the return value of
toUpperCase(),replace(),strip()and friends. - Calling methods on a
nullstring, which throwsNullPointerException. Check fornullor use"literal".equals(variable). - Off-by-one errors with
substring's exclusive end index. - Building large strings with
+=in a loop.
What's next#
That completes the fundamentals! You can write real procedural programs. Next we enter the world of object-oriented programming, starting with classes and objects.
Check your understanding
Quick quiz
1.What does this print?
String s = "java"; s.toUpperCase(); System.out.println(s);2.What is
"Elephantoo".substring(2, 5)?3.Why is
StringBuilderpreferred for building a string inside a large loop?
Finished reading?
Mark this lesson complete to track your progress.