You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.

It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).

Answer from sjr on Stack Overflow
🌐
Medium
medium.com › @thilinajayawardana_85346 › java-string-nullpointerexception-safe-equals-check-404481934e9b
Java String NullPointerException safe equals check | by Thilina Jayawardana | Medium
June 30, 2020 - This is because, in the if condition, you are first using the unknown string’s equals method to compare the other string. In this case, the unknown string is null, which means it doesn’t exist. Thus a NullPointerException.
Discussions

Java comparison == is not null-safe?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
41
16
February 21, 2024
Best Way to Check if a String is Null or Empty in Java - TestMu AI Community
What is the best way to check if a String is null or empty in Java? I’m currently parsing HTML data, and sometimes the String can be null or empty when the expected word doesn’t match. To handle this, I wrote the follow… More on community.testmuai.com
🌐 community.testmuai.com
0
February 1, 2025
java - Is "use "abc".equals(myString) instead of ...
11 When comparing a string variable to a string literal with .equals(), is there a standard practice for the order of items? -2 Question about the Java objects' equals() method · 128 Why use Optional in Java 8+ instead of traditional null pointer checks? More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 24, 2016
java - Compare Strings avoiding NullPointerException - Stack Overflow
@saumilsdk It is not possible to call null.equals(string). In case both Strings are a variable you need to call != null on the first one in order to avoid the exception. More on stackoverflow.com
🌐 stackoverflow.com
🌐
TechVidvan
techvidvan.com › tutorials › java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - String Literal : It can be applied ... unique comparison logic. Null Safety: If you try to use equals() on a null reference, it will return false rather than throwing an exception....
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.
🌐
TestMu AI Community
community.testmuai.com › ask a question
Best Way to Check if a String is Null or Empty in Java - TestMu AI Community
February 1, 2025 - What is the best way to check if a String is null or empty in Java? I’m currently parsing HTML data, and sometimes the String can be null or empty when the expected word doesn’t match. To handle this, I wrote the following check: if(string.equals(null) || string.equals("")){ Log.d("iftrue", "seem to be true"); }else{ Log.d("iffalse", "seem to be false"); } However, when I remove string.equals(""), the condition doesn’t work correctly.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › equals
Java String equals() - Compare Strings Equality | Vultr Docs
December 23, 2024 - Consequently, the equals() method returns false. Understand that invoking equals() on a null reference will throw a NullPointerException. Perform a null check before using equals() for comparison.
🌐
Coderanch
coderanch.com › t › 387952 › java › avoid-null-pitfalls-comparing-Strings
How do I avoid null pitfalls when comparing Strings? (Beginning Java forum at Coderanch)
February 7, 2001 - If any is then don't do the comparison. If none of them is null, use the eqauls() method to do your comparison. Good luck, Bosun · Bosun (SCJP, SCWCD). So much trouble in the world -- Bob Marley ... The way to compare String object contents is to use the equals() method.
🌐
Qlik Community
community.qlik.com › t5 › Talend-Studio › Handling-nulll-while-doing-equals-function › td-p › 2326825
Handling nulll while doing equals function - Qlik Community - 2326825
February 4, 2017 - As we know equals function (var1.equals(var2)) does not handle null values and it thows "null pointer exception ".In other words , both variables should have values only then it can work .If I used two equals function (==) function It is not giving expected result as we know the reason. I am looking for that solution where I can compare null String with a value var1="2016-01-03 11:05:07" var2=null ... Ditto - same here! ... use the java ternary operator.
🌐
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 - A null String in Java is literally equal to a reserved word “null”. It means the String that does not point to any physical address.” In Java programming language, a “null” String is used to refer to nothing.
🌐
Quora
quora.com › How-do-perform-a-Null-check-for-string-in-Java
How do perform a Null check for string in Java? - Quora
Null-checking a String in Java means ensuring it is not null before using it (to avoid NullPointerException) and — often — also checking for emptiness or whitespace-only content.
🌐
How to do in Java
howtodoinjava.com › home › string › java string.equals()
Java String.equals() with Examples - HowToDoInJava
January 9, 2023 - The equals() does not support null argument and throws NullPointerException. String str1 = "alex"; Assertions.assertThrows(NullPointerException.class, () -> { str1.contains(null); }); The following Java program demonstrates that equals() method ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.equals
String.Equals Method (System) | Microsoft Learn
public: virtual bool Equals(System::String ^ value); ... The string to compare to this instance. ... true if the value of the value parameter is the same as the value of this instance; otherwise, false. If value is null, the method returns false.
🌐
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.
🌐
Reddit
reddit.com › r/javahelp › how to resolve the error:java.lang.nullpointerexception: cannot invoke "string.equals(object)" because "condition" is null.
Cannot invoke "String.equals(Object)" because "condition ...
March 31, 2023 -

I am writing a program for Servlets and coming across an error:

java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "condition" is null.

What I am trying to here is to print the form as a response to the client if the terms and conditions are not met.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   version="4.0">
    
    <servlet>
        <servlet-name>
            first
        </servlet-name>
        <servlet-class>
            com.servlets.MyServlet
        </servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>
            first
        </servlet-name>
        <url-pattern>
            /RegisterServlet
        </url-pattern>
    </servlet-mapping>
    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Form Page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style >
            .container{
                width:40%;
                border:1px solid black;
                margin:auto;
                padding:20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1 style="text-align:center">My Form</h1>
            <form action="RegisterServlet" method="post">
                <table>
                    <tr>
                        <td>Enter your name</td>
                        <td><input type="text" name="user_name" placeholder="Enter here"></td>
                    </tr>
                    <tr>
                        <td>Enter the password:</td>
                        <td><input type="password" name="user_password" placeholder="Enetr the password"></td>
                    </tr>
                    <tr>
                        <td>Enter your email:</td>
                        <td><input type="email" name="user_email" placeholder="Enter your email"></td>
                    </tr>
                    <tr>
                        <td>Select Gender:</td>
                        <td><input type="radio" name="user-gender" value="male">Male &nbsp;&nbsp;<input type="radio" name="user-gender" value="female">Female</td>
                    </tr>
                    <tr>
                        <td>Select your course:</td>
                        <td>
                            <select name="user-course">
                                <option value="Java">Java</option>
                                <option value="C">C</option>
                                <option value="C++">C++</option>
                                <option value="PHP">Php</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td style="text-align:center">
                            <input type="checkbox" value="checked" name="condition"/>
                        </td>
                        <td>
                            Agree terms and conditions
                        </td>
                    </tr>
                    <tr>
                        <td>
                            
                        </td>
                        <td>
                            <button type="submit">Register</button>
                            <button type="reset">Reset</button>
                        </td>
                    </tr>
                </table>
                
            </form>
        </div>
    </body>
</html>

MyServlet.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author PC
 */
public class MyServlet extends HttpServlet {

    /**
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
        response.setContentType("text/html");
        // Writing the message on the web page      
        PrintWriter out = response.getWriter();      
        out.println("<h2>Welcome to servlet</h2>");   
        
        String name=request.getParameter("user_name");
        String password=request.getParameter("user_password");
        String email=request.getParameter("user_email");
        String gender=request.getParameter("user_gender");
        String course=request.getParameter("user_course");
        
         String condition=request.getParameter("condition");
         if(condition!=null){
            if(condition.equals("checked")){
                out.println("<h2>"+"Name:"+name+"</h2>");
                out.println("Password:"+password);
                out.println("Email:"+email);
                out.println("Gender:"+gender);
                out.println("Course:"+course);
             
            }else{
                out.println("The terms and conditions have not been agreed upon");
            }
         }
         else{
             out.println("The terms and conditions have not been agreed upon");
             RequestDispatcher rd=request.getRequestDispatcher("index.html");
             rd.include(request,response);
         } 
    }      
}
Top answer
1 of 3
8
Exceptions usually includes the linenumber where the exception is thrown, it may help you pinpoint the location. A tip in general, if you use string equals in the oposite order (ie "checked".equals(condition)) you have null safe expression, you would not need to to do an explicit null check of the condition.
2 of 3
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 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. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar 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: 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.
🌐
Devtalk
forum.devtalk.com › backend developer forum › backend questions/help
Java equals() selection - Backend Questions/Help - Devtalk
August 28, 2022 - In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string: MY CONSTANT ST…
🌐
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.