Replace null with empty String in Java [2 ways]

In this post, I will be sharing how to replace null with empty String in Java. There are two ways to achieve our goal of replacing null with empty String in Java.

1. Using String class replace() method to replace null with empty String

2. Using the ternary operator

Read Also: Null Character Java

Replace null with empty String in Java

1. Using the String class replace() method


We can easily use the String class replace() method to replace null with empty String in Java as shown below in the example:

One liner:


str = str.replace(null, "");


Let's say you are getting a list of strings from the database. If any string in the list of strings is null then replace it with empty String.

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

public class ReplaceNullWithEmptyString {
    public static void main(String args[]) {
        List<String> listOfCurrencies = Arrays.asList(new String[]{"Rupee","Dollar",null,"Yen",null}); 
        System.out.println("List of Currencies with null: " + listOfCurrencies);
        List<String> listOfCurrenciesWithoutNull = new ArrayList<>();
        for(String currency : listOfCurrencies)
        {
            currency = replaceNull(currency);
            listOfCurrenciesWithoutNull.add(currency);
        }
        System.out.println("List of Currencies with empty string: " + listOfCurrenciesWithoutNull);
    }
    
    public static String replaceNull(String s)
    {
        return (s == null)? "" : s;
    }
}


Output:
List of Currencies with null: [Rupee, Dollar, null, Yen, null]
List of Currencies with empty string: [Rupee, Dollar, , Yen, ]

In the above output, we have replaced all the null values with empty String. Also, the method replaceNull() is returning a String value using a ternary operator. In simple words, it means if the String is null then return an empty String else return the same String.

2. Print empty String rather than null using the ternary operator


If you want to print an empty String rather than null in Java then we can use the ternary operator as shown below in the example:

public class ReplaceNullWithEmptyString2 {
    public static void main(String args[]) {
        String s1 = null;
        System.out.println("String is: "+ (s1 == null ? "" : s1));
        String s2 = "Dollar";
        System.out.println("String is: "+ (s2 == null ? "" : s2));
    }
}


Output:
String is:
String is: Dollar

That's all for today. Please mention in the comments if you have any questions related to how to replace null with empty String in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry