Explain Codes LogoExplain Codes Logo

Concatenating null strings in Java

java
string-concatenation
null-pointer-exceptions
compiler-optimizations
Nikita BarsukovbyNikita Barsukov·Feb 2, 2025
TLDR

One quick solution to handle null values during string concatenation in Java is to use Objects.toString(). The null converts to a custom empty string, effectively eliminating the "null" in output.

String a = null; String b = "Hello"; String result = Objects.toString(a, "") + b; // Produces "Hello"

Handling null with grace

In Java, a null string elegantly integrates with the string concatenation process, thanks to the JLS 8 § 15.18.1. For instance:

String a = null; // Yep, there's a null here String b = " world"; String result = a + b; System.out.println(result); // Will print "null world" instead of blowing up!

The bytecode handles concatenating null strings as if using a StringBuilder, making the output "null world" in our case.

Behind the scenes: Compiler optimizations

Sometimes, Java compiler optimizations kick in during string concatenation, implementing various performance-enhancement techniques like using a StringBuffer interchangeably with a StringBuilder. This optimization is beneficial when dealing with large-scale string processing tasks, making Java less of a "coffee-break" language.

StringBuilder sb = new StringBuilder(); sb.append(a); // Smooth as butter, even when a is null sb.append(b); // " world" String result = sb.toString(); // "null world" or " world" depending on a's mood

Ready to combat "null": Practical use cases

To fortify your code against the spooky NullPointerExceptions coming to haunt your code, consider this icing on the cake:

StringBuilder sb = new StringBuilder(); sb.append(a == null ? "" : a); sb.append(b); String result = sb.toString(); // result won't echo "null" like a haunted house

Alternatively, you can go defensive with ternary operations:

String result = (a == null ? "" : a) + (b == null ? "" : b); // "null" isn't invited

Or, invite the Apache Commons StringUtils to your party:

String result = StringUtils.defaultString(a) + StringUtils.defaultString(b); // Party on!

Null: A necessary evil

Handling edge cases and gotchas

Null can play hide-and-seek with NullPointerExceptions when invoking methods on seemingly harmless strings. Also, collections or arrays of Strings might return unexpected "null" surprises on concatenation – a little like finding raisins in what you thought was a chocolate chip cookie.

Alternative approaches

Remember, there is always more than one way to skin a cat. Here are two alternative ways to tackle null when concatenating strings using join from String class or streams:

String joined = String.join("", a, b, c); // "HelloWorld" even when b is feeling null-ish

Or, elegantly filter out null values with streams:

String result = Stream.of(a, b, c) .filter(Objects::nonNull) .collect(Collectors.joining()); // Result is a "null"-free "HelloWorld"

The role of null in your life

While null might appear like a villain, remember - every villain has a backstory. By understanding how to deal with null in string operations, you can write more robust and error-tolerant code. It's like learning to deal with an annoying co-worker – not fun, but necessary.