You're trying to call the isEmpty() method on a null reference (as List test = null;). This will surely throw a NullPointerException. You should do if(test!=null) instead (checking for null first).

The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).

You may want to see this question.

Answer from Lion on Stack Overflow
๐ŸŒ
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 - Consider the following example. String str = " "; if (str.isBlank()) { System.out.println("String is blank"); } Checks if the value is null, empty, or contains only whitespace characters.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java array โ€บ checking if an array is null or empty in java
Checking if an Array Is Null or Empty in Java | Baeldung
July 16, 2024 - Since primitiveArray.getClass().isArray() is true, isEmpty() works for primitive type arrays. Checking if an array is null or empty is a fundamental task in Java programming. In this article, weโ€™ve explored how to implement these checks for both object and primitive type arrays, creating a robust utility method that can be reused in our applications.
๐ŸŒ
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 - Explore practical examples that showcase these techniques to help you integrate them into your Java applications seamlessly. Use the basic logical operations directly to check if a string is null or empty. ... public static boolean isNullOrEmpty(String str) { if (str == null || str.isEmpty()) { return true; } return false; } Explain Code
๐ŸŒ
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 a string with white spaces String str = " "; // check if str1 is null or empty System.out.println("str is " + isNullEmpty(str)); } // 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 if (str.trim().isEmpty()){ return "EMPTY"; } else { return "neither NULL nor EMPTY"; } } }
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ why does the order of string == null || string.isempty() matter? or does it?
r/learnjava on Reddit: Why does the order of String == null || String.isEmpty() matter? Or does it?
May 3, 2019 -

I just completed MOOC, Java part II, exercise 19 for week 9 and found that the order I placed name.isEmpty() or name == null was the key to get it's tests to pass.

The test which failed was one that tested a null but I don't understand why it matters since it's an or statement.

Thank You

So this fails

    public Person(String name, int age) {
        if ( name.isEmpty() || name == null ||  name.length() > 40) {
            throw new IllegalArgumentException("Name is an invalid length.");
        } else {
            this.name = name;
        }

        if ((age < 0) || (age > 120)) {
            throw new IllegalArgumentException("Age is not a valid range");
        } else {
            this.age = age;
        }
    }

But this passes

    public Person(String name, int age) {
        if (  name == null || name.isEmpty() || name.length() > 40) {
            throw new IllegalArgumentException("Name is an invalid length.");
        } else {
            this.name = name;
        }

        if ((age < 0) || (age > 120)) {
            throw new IllegalArgumentException("Age is not a valid range");
        } else {
            this.age = age;
        }
    }
๐ŸŒ
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. In the below program, we are checking whether the string is null or empty. ... The String is empty is returned for the first case because str==null is true, and in the second case the condition str1.isEmpty() is true that's why the String is empty is returned.
Find elsewhere
๐ŸŒ
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)
However, if you set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true, the value of the managed bean attribute is passed to the Bean Validation runtime as a null value, causing the @NotNull constraint to fail. ... 48.4.3.4 To Build, Package, and Deploy the hello1-formauth Example Using Maven and the asadmin Command
๐ŸŒ
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 - Java provides a built-in method to check for all those whitespaces in a String. Letโ€™s look at an example on how to use that. public class Example2 { public static void main(String[] args) { // check if it is a "blank" string String myName = new String(" \t \n \t \t "); System.out.println("The String = " + myName); System.out.println("Is the String null? " + (myName == null)); System.out.println("Is the String empty? " + myName.isEmpty()); System.out.println("Is the String blank?
๐ŸŒ
Java Guides
javaguides.net โ€บ 2019 โ€บ 04 โ€บ check-if-collection-is-empty-or-null-in-java.html
Check if a Collection is Empty or Null in Java
June 21, 2024 - The following example demonstrates how to check if a Map is null or empty: import java.util.HashMap; import java.util.Map; public class CheckMap { public static void main(String[] args) { Map<String, Integer> map = null; // Check if the map is null or empty if (map == null || map.isEmpty()) { System.out.println("The map is null or empty."); } else { System.out.println("The map is not null and not empty."); } // Initialize the map map = new HashMap<>(); // Check if the map is null or empty if (map == null || map.isEmpty()) { System.out.println("The map is null or empty."); } else { System.out.println("The map is not null and not empty."); } // Add an entry to the map map.put("Apple", 1); // Check if the map is null or empty if (map == null || map.isEmpty()) { System.out.println("The map is null or empty."); } else { System.out.println("The map is not null and not empty."); } } }
๐ŸŒ
W3Docs
w3docs.com โ€บ java
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. Here is an example of how the isEmpty() method can be used:
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ home โ€บ java/lang โ€บ java string isempty method
Java String isEmpty Method
September 1, 2008 - Because Null is a placeholder that generally means, "no data is available about this", and it is not the same as an empty string, the compiler cannot handle it and throws a NullPointerException. Following is the syntax of the Java String isEmpty() method โˆ’
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ question about .isempty() and .contains("")
r/learnjava on Reddit: Question about .isEmpty() and .contains("")
July 25, 2023 -

SORRY

I JUST REALISED I MADE A MISTAKE I WANTED TO ASK ABOUT EQUALS("") BUT AT THE SAME TIME I WAS FIGHTING WITH ANOTHER EXCERCISE IN WHICH I HAD TO USE CONTAINS() METHOD AND THIS MESSED UP MY THOUGHTS SORRY FOR WASTING YOUR TIME :/

but still i was able to get some usefull info about contains method so it wasn't as much wasted effort but still sorry

Hi i'm doing(or atleast trying to do) mooc.fi java part 1 course and there in some exercises is required to check for empty input.

So there is my question what is difference between .isEmpty() and .Equals("") because i like to use the first one but in suggested solutions always is used ".Equals("") and i'm wondering is there any rule for using .isEmpty(), maybe it's the matter of optimalization etc. or maybe both are as good

I know it can be stupid question but it's better to ask that and get rid of bad habits in writing code as soon as possible :D

In advance thanks for answers

P.S i hope everything is easy to understand unfortunately my english is still far from good :D

Top answer
1 of 5
2
isEmpty() checks for string length and returns true if it's zero, while contains("") will return true unless the string isn't initialized/null. For checking empty strings or strings containing only whitespace you could also use the method isBlank(). Hope this helps!
2 of 5
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 501509 โ€บ java โ€บ difference-null-isEmpty
The difference between null and isEmpty. (Beginning Java forum at Coderanch)
One tests if the ArrayList variable is null, the other if the ArrayList object holds any items in its list. You would test for null first, and then if not null, check if its empty or not. The reason to do it in this order is if you test if its empty and it happens to be null, you'll throw a NullPointerException for trying to call a method on a null object.
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2017 โ€บ 10 โ€บ java-string-isempty-method-with-example
Java String isEmpty() method
public class Example{ public static void main(String args[]){ String str1 = null; String str2 = "beginnersbook"; if(str1 == null || str1.isEmpty()){ System.out.println("String str1 is empty or null"); } else{ System.out.println(str1); } if(str2 == null || str2.isEmpty()){ System.out.println("String ...