If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

Answer from user281377 on Stack Exchange
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

🌐
Oracle
docs.oracle.com › javaee › 7 › tutorial › bean-validation002.htm
21.2 Validating Null and Empty Strings - Java Platform, Enterprise Edition: The Java EE Tutorial (Release 7)
if (testString==null) { doSomething(); } else { doAnotherThing(); } By default, the doAnotherThing method is called even when the user enters no data, because the testString element has been initialized with the value of an empty string. In order for the Bean Validation model to work as intended, you must set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true in the web deployment descriptor file, web.xml:
Top answer
1 of 4
3

For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:

if("constantString".equals(COMPLETEDDATE)) {
    // logic
}

But in general, your approach isn't correct.

The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.

The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.

Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.

Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".

2 of 4
1

To check null string you can use Optional in Java 8 as below: import Optional

import java.util.Optional;

import it as above

String str= null;
Optional<String> str2 = Optional.ofNullable(str);

then use isPresent() , it will return false if str2 contains NULL otherwise true

if(str2.isPresent())
{
//If No NULL 
}
else
{
//If NULL
}

reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

Top answer
1 of 3
1

Assign null

When we write:

String s = "Hello World!";
s = null;

The String object still exists in memory because this does not delete it. However the garbage collector will clear the object from memory as there is no variable referencing it.
For all practical purposes s = null; deletes the String.

2 of 3
0

tl;dr

set a String to null in Java?

myString = null ;

declare the variable without initializing it

Uninitialized deaults to null, no String object. Empty reference variable.

String myString ;  

You can explicitly assign null. Same effect as line above. No object, empty reference.

String name = null;

Declare and initialize to empty string:

String myString = "" ;  // A `String` object containing no characters. Not null.

Details

Before posting here on basic Java Questions, study the Java Tutorials provided by Oracle free of cost.

See the tutorial page on string literals. To quote:

There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

So null is not a piece of text with four characters. The keyword null means “no object at all”, no String, nothing at all, an empty reference.

To test if an object reference variable is null (contains no reference), you have a few choices:

  • Objects.isNull( myVar ) and Objects.nonNull( myVar )
  • null == myVar and null != myVar
  • myVar == null and myVar != null

I prefer the first, as words are easier to read than mathematical-like symbols.

🌐
LabEx
labex.io › tutorials › java-how-to-handle-null-values-when-joining-java-strings-417590
How to handle null values when joining Java strings | LabEx
The simplest approach to handle null values is to check for null before performing operations: Create a new Java file named BasicNullHandling.java in the /home/labex/project directory.
🌐
GeeksforGeeks
geeksforgeeks.org › java › program-to-check-if-the-string-is-null-in-java
Program to check if the String is Null in Java - GeeksforGeeks
July 12, 2025 - To check if a string is null in Java, we can use the "==" operator that directly compares the string reference with null.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - In the following sections, we’ll discuss other ways of handling null validations. It’s usually a good practice to write code that fails early. So, if an API accepts multiple parameters that aren’t allowed to be null, it’s better to check for every non-null parameter as a precondition of the API. Let’s look at two methods — one that fails early and one that doesn’t: public void goodAccept(String one, String two, String three) { if (one == null || two == null || three == null) { throw new IllegalArgumentException(); } process(one); process(two); process(three); } public void badAccept(String one, String two, String three) { if (one == null) { throw new IllegalArgumentException(); } else { process(one); } if (two == null) { throw new IllegalArgumentException(); } else { process(two); } if (three == null) { throw new IllegalArgumentException(); } else { process(three); } }
Find elsewhere
🌐
CodeGym
codegym.cc › java blog › strings in java › java: check if string is null, empty or blank
Java: Check if String is Null, Empty or Blank
October 11, 2023 - Very often in programming, a String is assigned null to represent that it is completely free and will be used for a specific purpose in the program. If you perform any operation or call a method on a null String, it throws the java.lang.NullPointerException. Here is a basic example illustrating declaration of a null String.
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Improper handling of method arguments. Not validating method arguments for null values. Incorrect use of collections. Assuming collections are always non-null, leading to NullPointerExceptions. Neglecting thread safety. Overlooking that null checks in multi-threaded environments can lead to race conditions. ... Initialize variables. Always initialize reference variables when they’re declared. ‍ --CODE language-markup-- String myStr = ""; // Instead of null Perform null checks.
🌐
Reddit
reddit.com › r/java › cleanest way to check for null on a string?
Cleanest way to check for null on a String? : r/java
May 8, 2024 - D is correct by chance : you switch the String.valueOf() call to obj.toString and I had to look the doc "if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned." If it was a pure replacement I would raise an eyebrow during code review, but that code is 100% correct. [EDIT] Why are you even converting unknown type of elements into String? In real-life situations, I would recheck the requirements. ... News, Technical discussions, research papers and assorted things of interest related to the Java programming language NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java
🌐
Programiz
programiz.com › java-programming › examples › string-empty-null
Java Program to Check if a String is Empty or Null
class Main { public static void main(String[] args) { // create null, empty, and regular strings String str1 = null; String str2 = ""; String str3 = " "; // check if str1 is null or empty System.out.println("str1 is " + isNullEmpty(str1)); // check if str2 is null or empty System.out.println("str2 is " + isNullEmpty(str2)); // check if str3 is null or empty System.out.println("str3 is " + isNullEmpty(str3)); } // method check if string is null or empty public static String isNullEmpty(String str) { // check if string is null if (str == null) { return "NULL"; } // check if string is empty else
Top answer
1 of 16
187

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.


Longer answer:

If you try this, it won't work, as you've found:

String foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

What you probably wanted was:

String foo = null;
if (foo == null) {
    // That will work.
}

The typical way to guard yourself against a null when dealing with Strings is:

String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

The easy way, if you're using a String literal (instead of a variable), is:

String foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

if (StringUtils.equals(foo, bar)) {
    // Do something here.
}

Another response was joking, and said you should do this:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

2 of 16
33
s == null

won't work?

🌐
Stack Abuse
stackabuse.com › java-check-if-string-is-null-empty-or-blank
Java: Check if String is Null, Empty or Blank
February 28, 2023 - String string = "Hello there"; if (string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank"); In much the same fashion as the before, if the trimmed string is "", it was either empty from the get-go, or was a blank string with 0..n whitespaces: ... The Apache Commons is a popular Java library that provides further functionality. StringUtils is one of the classes that Apache Commons offers. This class contains methods used to work with Strings, similar to the java.lang.String.
🌐
Medium
medium.com › @ecetasci.iu › checking-for-null-or-empty-strings-in-java-19518fa1e553
Checking for Null or Empty Strings in Java | by Ece Tasci | Medium
February 25, 2025 - In Java, calling a method on a null reference will result in a NullPointerException, one of the most common runtime errors. To prevent this, it is crucial to check for null before performing operations on a variable. An empty String ("") has zero characters but still exists in memory, specifically in the heap where Java stores objects.
Top answer
1 of 3
11

First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

public static void main (String args[]){
    String s;       
    System.out.println(s); // compiler error variable may not be initialized
}

vs

public static void main (String args[]){
    String s=null;      
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize it.

That being clear, I would recommend you to use a "smart default". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program produce an exception because it indicates something wrong happened under the hood that should not have happened.

2 of 3
8

In general you want to keep declaration and initialisation as close as possible to minimise exactly the type of problem you're talking about.

There is also the issue of redundant initialisation where the value null you're assigning is never used which is extra code that harms readability even if the redundant assignment is optimised away by the compiler.

Sometimes assigning some sort of default value is unavoidable, for example if you declare before a try catch, initialise inside and use it afterwards. For other types you can often find a more natural default value such as an empty list.

🌐
LabEx
labex.io › tutorials › java-how-to-check-if-a-string-is-null-in-java-559988
How to Check If a String Is Null in Java | LabEx
Learn how to check if a string is null in Java using the equality operator, combine null and empty checks, and leverage the Optional class for safe null handling. Master essential Java string null checks.
🌐
Codemia
codemia.io › knowledge-hub › path › checking_if_a_string_is_empty_or_null_in_java
Checking if a string is empty or null in Java
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
List<String> list = new ArrayList<>(); list.add(null); list.forEach(System.out::println); // handle nulls carefully · Null and Default Values: Use null to signify optional parameters in methods. public void exampleMethod(String param1, String param2) { if (param2 == null) { param2 = "default"; ...
🌐
Coderanch
coderanch.com › t › 522022 › java › parse-null-string-null
How to parse null string to null. (Beginning Java forum at Coderanch)
You will want a validator to notice invalid value null for a last name, where "null" would be accepted as a valid last name... A third example is when you explicitly do not want your application to store the string "null" in a database's nullable (var)char field.