String Handling in Java
A walkthrough of common string handling in Java: string comparison, null-safe operations, blank checks, and everyday string utilities, comparing the older StringUtils approach with modern JDK built-in methods.
String handling is a common task in any programming language. Java is often considered verbose, and not only are all variables strongly typed, but string handling can also be cumbersome. A careless mistake can easily lead to a NullPointerException and crash your program. This article summarizes the common ways to handle strings in Java. Earlier projects often relied on StringUtils, while newer Java versions have added many built-in alternatives.
1. How Java Compares Strings
Java usually uses the .equals() method to compare strings. .equals() is a method of the String class itself, so if the string is null, calling it causes a NullPointerException.
A common string comparison:
1
2
3
String s1 = "foo";
String s2 = "bar";
s1.equals(s2); // false
A comparison that throws a NullPointerException:
1
2
3
String s1 = null;
String s2 = "bar";
s1.equals(s2); // NullPointerException
2. Why You Can’t Use ==
In Java, == does not compare the value of strings. It compares memory references.
Java has never changed == to compare string contents. The main reason is that == is defined uniformly for all objects as a reference comparison. This is a fundamental language rule. Changing it to behave differently for strings alone would make the language inconsistent and would break the existing semantics and compatibility of countless programs. So == always compares references, meaning whether two variables point to the same object in memory.
Why == sometimes seems to work:
- Literals happen to be in the String Pool
1
2
3
4
5
6
7
8
9
10
String a = "hello";
String b = "hello";
a == b; // true, because both point to the same object in the pool
String c = "hel" + "lo"; // Compile-time constant, the compiler merges it into "hello"
a == c; // true
String d = "hel";
String e = d + "lo"; // Concatenated at runtime, creates a new object
a == e; // false!
Tests that use literals often “happen to pass.” Then, once data comes from a database or an API in production, things break. This is the classic trap.
- Since Java 7, switch supports strings
1
2
3
4
switch (status) {
case "ACTIVE" -> ...;
case "INACTIVE" -> ...;
}
It looks like a direct comparison, but the compiler implements it with hashCode() and equals(), not ==. (Also note that if status is null, it throws an NPE. Java 21’s pattern matching for switch lets you write case null.)
- In Kotlin, == is equals
If your team uses Kotlin, or you have read Kotlin code, you know that in Kotlin == calls equals(), and === is the reference comparison. But that’s Kotlin, not Java.
3. Common String Handling Built into Java
Null-safe comparison
1
Objects.equals(a, b); // Java 7
Objects.equals(a, b) first checks whether a is null. If both are null, it returns true, so it never throws a NullPointerException.
Joining a list into a string
1
String.join(",", list); // Java 8
A similar approach is to use
spliton a String to get an array, then useArraysto convert the array to aList:List<String> list = Arrays.asList(s.split(","));Arrays.asList()appeared in Java 1.2,.split(",")came in Java 1.4, a bit later thanArrays.asList(), while theList<String>generic type appeared only in Java 5. When maintaining systems on older Java versions, check which features are available in your target version.
If you are joining inside a Stream pipeline, you can use Collectors.joining:
1
list.stream().collect(Collectors.joining(",")); // Java 8
Replacing null with a default value
1
Objects.requireNonNullElse(s, ""); // Java 9
Checking for blank strings
Java 11 added a built-in method for blank checks. It works even when the string contains only whitespace, such as " ", but the string itself must not be null.
1
s.isBlank(); // Java 11, but s must not be null
isEmpty()has been around since Java 6. It checks whether the string length is 0.isBlank()took much longer to arrive.
Trimming leading and trailing whitespace
1
s.strip(); // Java 11
trim()has been available since Java 1.0. It removes leading and trailing whitespace, but it only handles ASCII whitespace (characters ≤ U+0020). Full-width spaces are not removed. To handle full-width spaces,strip()is recommended.
Repeating a string
1
"ab".repeat(3); // Java 11, result is "ababab"
Splitting by lines
1
"a\nb\nc".lines().forEach(System.out::println); // Java 11
lines() splits a string at line terminators (\n, \r, or \r\n) and returns a Stream<String>. It is well suited for processing multi-line text line by line, without writing your own split("\n") and worrying about Windows \r\n line endings.
Formatting strings
1
"Hello, %s!".formatted("Mark"); // Java 15, result is "Hello, Mark!"
formatted() is the instance-method equivalent of String.format(...). It reads more naturally and pairs well with text blocks.
4. How Earlier Java Projects Handled Strings
Spring Boot began largely replacing traditional stacks around 2018 and became the mainstream framework for Java back ends. Before that, Spring MVC was the common choice, roughly between 2010 and 2016. Earlier still was the SS2H era: Spring + Struts 2 + Hibernate.
Java 8 was released in 2014 and went on to become a long-term support version used by many enterprise projects.
So how did earlier projects compare and process strings?
Surely every project didn’t hand-roll everything, right?
This is where the early Apache project StringUtils comes in.
Apache Commons Lang3 StringUtils
Apache Commons Lang is a Java utility library provided by the Apache Software Foundation. Its org.apache.commons.lang3.StringUtils class is dedicated to string handling. Its biggest feature is that every method is null-safe: passing in null does not throw a NullPointerException.
To add it with Maven (use the latest stable version):
1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>latest-version</version>
</dependency>
Common usage examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.apache.commons.lang3.StringUtils;
StringUtils.isBlank(null); // true, both null and whitespace count as blank
StringUtils.isBlank(" "); // true
StringUtils.isNotBlank("foo"); // true
StringUtils.isEmpty(""); // true, only checks for null or zero length
StringUtils.equals(null, null); // true
StringUtils.defaultString(null); // ""
StringUtils.defaultIfBlank(" ", "N/A"); // "N/A"
StringUtils.strip(" abc "); // "abc"
StringUtils.repeat("ab", 3); // "ababab"
StringUtils.join(list, ","); // joins the list with ","
StringUtils.substringBetween("[abc]", "[", "]"); // "abc"
StringUtils.abbreviate("Hello World", 8); // "Hello..."
When you should still use StringUtils
- If your project already includes commons-lang3, just keep using it. There’s no need to rewrite large amounts of code just to replace it.
- If you maintain a project that targets Java 8 or earlier, or one that cannot be upgraded to Java 11 or later.
- If your team prefers the null-safe style of
isBlankandisEmptyand wants to reduce defensive null checks.
StringUtils vs. native Java
| Requirement | Older StringUtils | Modern JDK built-in |
|---|---|---|
| Null-safe comparison | StringUtils.equals(a, b) | Objects.equals(a, b) (Java 7) |
| Null or empty check | StringUtils.isEmpty(s) | s == null \|\| s.isEmpty() (Java 6; isEmpty() can be called directly only when s is not null) |
| Blank check | StringUtils.isBlank(s) | s.isBlank() (Java 11, but s must not be null) |
| Trim leading and trailing whitespace | StringUtils.strip(s) | s.strip() (Java 11) |
| Repeat a string | StringUtils.repeat("ab", 3) | "ab".repeat(3) (Java 11) |
| Join | StringUtils.join(list, ",") | String.join(",", list) (Java 8) |
| Null to default value | StringUtils.defaultString(s) | Objects.requireNonNullElse(s, "") (Java 9) |
| Default value for blank | StringUtils.defaultIfBlank(s, "N/A") | (s == null \|\| s.isBlank()) ? "N/A" : s (Java 11) |
In short, for new projects, prefer the JDK’s built-in methods to reduce dependencies. For older projects, or when you need a lot of null-safe checks, StringUtils is still a practical choice.
Conclusion
Java string handling can be summarized in a few key points:
- Compare contents with
equals(), not==. If a variable might benull, useObjects.equals()or the corresponding StringUtils method. - Java 8 and later versions added many built-in methods, such as
String.join,isBlank,strip,repeat,lines, andformatted. Most common needs no longer require an extra library. - StringUtils was an important tool in the early Java ecosystem. Understanding it helps you read legacy code and quickly choose a null-safe option when needed.
- Watch for version compatibility. When maintaining older systems, confirm the JDK version before deciding which approach to use.