No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.

Your test should be:

if (acct != null && !acct.isEmpty())

Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.

Alternatively, using Guava:

if (!Strings.isNullOrEmpty(acct))
Answer from Jon Skeet on Stack Overflow
🌐
Sumo Logic
sumologic.com › log search › search query language › search operators › isnull, isempty, isblank
isNull, isEmpty, isBlank Search Operators | Sumo Logic Docs
... The isNull operator checks a string and returns a boolean value: true if the string is null, or false if the string is not null. The isEmpty operator checks if a string contains no characters and is only whitespace.
🌐
Medium
medium.com › @lp.lok.payu › isempty-vs-empty-vs-isblank-vs-isnull-12aea580fe4b
isEmpty() vs empty() vs isBlank() vs isNull() | by leela prasad | Medium
February 16, 2025 - Advantages: Provides a clear and explicit check for null references, avoiding potential NullPointerException. Disadvantages: Requires an additional utility method or library, as it is not built-in.
🌐
Scaler
scaler.com › home › topics › isempty() in java
Java String isEmpty - Scaler Topics
January 4, 2024 - The isEmpty() method raises an exception if the string is null. We can simply avoid the exception by comparing the string value. Let's understand how to check if the string is null or empty.
🌐
W3Docs
w3docs.com › java
Does java.util.List.isEmpty() check if the list itself is null?
Does java.util.List.isEmpty() check if the list itself is null? No, the isEmpty() method of the java.util.List interface does not check if the list itself is null. It only checks if the list is empty, i.e. if it contains no elements.
🌐
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 - Note: It's important to do the ... all other conditions before it will throw a NullPointerException. The isEmpty() method returns true or false depending on whether or not our string contains any text....
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java string › checking for empty or blank strings in java
Checking for Empty or Blank Strings in Java | Baeldung
January 8, 2024 - The ObjectUtils class provides the isEmpty() method to check if a string is empty: ... Like Guava, it won’t check if a string only contains whitespace but checks whether a given string is null or empty.
Top answer
1 of 5
92

Generally, your lists should always be initialized. One common misconception is that queries can produce a null list, which is never true.

For example, consider the following code:

Account[] records = [SELECT Id, Name, AccountNumber FROM Account];
if(records!=null && !records.isEmpty()) {
    for(Account record: records) {
        // Do Something Here
    }
}

This is a waste of CPU time, because (a) records will never be null, and (b) iterating over an empty list is acceptable. Therefore, none of the three checks you might use are rarely appropriate. The only exception to this rule is when one query is used to fuel another query, in which case you would check for the presence of values before performing the query:

Account[] accounts = [SELECT Id, Name, AccountNumber FROM Account];
if(accounts.isEmpty()) {
    return;
}
Contact[] contacts = [SELECT Id, Name, Email FROM Contact WHERE AccountId IN :accounts];

For lists you create yourself, you should always initialize them before using them. This is true for other types, like sets and maps, as well. There are, however, times when you'll need to check for a specific condition before using some lists. It helps if you experiment with the various types to get a feel for when you should be aware that a list may be null.

For example, consider a variable that binds to a multi-select picklist:

public String[] selectedValues { get; set; }

In this case, selectedValues will either be null, or will not be empty. You only ever need to check for != null in this case. Part of becoming an efficient developer is recognizing the patterns in a system. If you're still using myVar != null && !myVar.isEmpty() as a condition, that generally means you're making one or even two checks too many.

There is always one correct condition to use in every situation. If this isn't true, that suggests that values were not properly initialized elsewhere.

Edit: Safe Navigation Operator

As a special exception, you can now use the Safe Navigation Operator to skip the null check. That looks like this:

if(records?.size() > 0) {
 /* Do something here */
}

Because of the changes brought in with the Safe Navigation Operator, when either size of the comparison is null, the result is false. If we want to abort early, then we can negate the entire thing:

if(!(records?.size() > 0)) {
  return;
}
2 of 5
14

It is generally best to avoid null values in code so using null list references to indicate empty lists isn't usually good approach. That is this code:

List<String> strings = new List<String>();
...
for (String item : strings) {
    ...
}

is clearer and safer than this code:

List<String> strings = null;
...
if (strings != null) {
    for (String item : strings) {
        ...
    }
}

So prefer empty lists to null list references.

Personally I find myList.size() > 0 to be clearer than !myList.isEmpty() because the latter amounts to "not is empty" which takes a moment to understand. But as people will use both forms get used to both.

🌐
GeeksforGeeks
geeksforgeeks.org › java › list-isempty-method-in-java-with-examples
List isEmpty() method in Java with Examples - GeeksforGeeks
December 3, 2024 - The isEmpty() method of the List interface in Java is used to check if a list is empty or not.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.isnullorempty
String.IsNullOrEmpty(String) Method (System) | Microsoft Learn
let test (s: string): string = if String.IsNullOrEmpty(s) then "is null or empty" else $"(\"{s}\") is neither null nor empty" let s1 = "abcd" let s2 = "" let s3 = null printfn "String s1 %s" (test s1) printfn "String s2 %s" (test s2) printfn "String s2 %s" (test s3) // The example displays the following output: // String s1 ("abcd") is neither null nor empty. // String s2 is null or empty. // String s3 is null or empty. For more information about this API, see Supplemental API remarks for String.IsNullOrEmpty.
🌐
Vultr Docs
docs.vultr.com › java › examples › check-if-a-string-is-empty-or-null
Java Program to Check if a String is Empty or Null | Vultr Docs
December 17, 2024 - Use StringUtils.isEmpty() to check ... StringUtils.isEmpty(str); } Explain Code · StringUtils.isEmpty() internally checks for null and empty strings, making your code cleaner and more expressive....
Top answer
1 of 3
14

The straight SOQL accounts = [select id, .. from Account ...]

always returns a list

You can usually avoid even having to test for list empty by coding your methods to accept lists as arguments and otherwise use for loop processing as in

for (Account a: accounts) { // if accounts is empty, loop does nothing
    // do work
}

someReturnType myMethod(Account[] accounts) {
   for (Account a: account) {
      // do work
   }
}

Otherwise use accounts.isEmpty() or accounts.size() == 0

testing for null is unnecessary in a well-designed application that uses lists and maps as the core internal data structures. Personally, if I ever get a null value for a list, I prefer the null exception to occur during unit testing as it means I didn't design my code correctly to operate with lists throughout (or I forgot to init a list to empty).

N.B.

For DML, you never need to test for list empty as SFDC will do nothing if passed an empty list

Use:

update accounts; // does not burn a DML limit if list is empty

Don't use (wastes a line of code):

if (!accounts.isEmpty())
   update accounts;
2 of 3
7

Generally speaking, null values should be rare, and you should treat them as such. The results of a query always results in a list, even though it may be an empty list. Querying a checkbox field from the database will always be true or false, never null. Calling XmlNode.getChildElements() will never return null, but may return empty lists.

There are a few rare exceptions when you do need to check for null values. For example, when you make a variable transient, its not stored in the view state, so you usually need to implement lazy loading by checking for null first, and when you bind to a multi-select picklist, the list will always be either null or non-empty.

These are the exceptions to the rule, and you should learn them. Whenever you declare a list of your own, you should always assign a non-null value to it, which may be either a new list, or a list generated from a query. You should prefer to initialize those lists in a constructor, so that all your initialization code is in one place.

Generally speaking, when I use a method I'm not familiar with, I try calling it with a few different parameters to see if I can get a null value back instead of a list. I test it independently to verify its behavior. If it doesn't return a null, then I presume it never will. Just remember that most of the API avoids returning null values, or has a way to check beforehand. Most of the best design patterns for code avoid nulls using various techniques. As you gain experience, you'll learn those rare times when you must check for null, and find ways to code structures to reduce the null checks you need to make.

🌐
Sentry
sentry.io › sentry answers › javascript › how do i check for an empty/undefined/null string in javascript?
How do I Check for an Empty/Undefined/Null String in JavaScript? | Sentry
To check that a value is not an empty string, null, or undefined, you can create a custom function that returns true if a value is null, undefined, or an empty string and false for all other falsy values and truthy values: ... function ...
🌐
Reddit
reddit.com › r/learnjava › shorter (efficient) way to check if a string is null or empty?
Shorter (efficient) way to check if a string is null or empty? : r/learnjava
March 1, 2020 - [The Java String class has an isEmpty ... doesn't crash. Yet, your advice is to let the application crash. That is in no way better than checking that the variable is null or empty....
🌐
iO Flood
ioflood.com › blog › stringutils-isempty
StringUtils.isEmpty() in Java: Your Method Guide
March 27, 2024 - At its core, StringUtils.isEmpty is a simple yet powerful tool in Java for checking if a string is empty or null.