Skip to main content

Java String NullPointerException safe equals check

If you compare two Strings in Java, normally you would use the equals method to compare them to see if they are similar.

This will be some common use case for input validations. However, if you don't do it properly it may cause you to throw a NullPointerException.

This is pretty much like common sense, but I've seen even more experienced developers make this mistake.

Let's consider the following code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class DemoApplication {

 final static String theStringIknow = "Hello";

 public static void myTestMethod(String someString) {
                //do not do this
  if (someString.equals(theStringIknow)) {
   System.out.println("Same same");
  }

 }

 public static void main(String[] args) {
  String testString = "Hello";

  myTestMethod(testString);

 }

}


In myTestMethod, I'm checking if the String in the argument equals to another String that I know.
This code works perfectly fine if you run it, but this is not the best way to do this.

For some reason, if the input String to myTestMethod happens to be null, then this will throw a NullPointerException.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class DemoApplication {

 final static String theStringIknow = "Hello";

 public static void myTestMethod(String someString) {
                //do not do this
  if (someString.equals(theStringIknow)) {
   System.out.println("Same same");
  }

 }

 public static void main(String[] args) {
  String testString = null;

  myTestMethod(testString);

 }

}

Exception in thread "main" java.lang.NullPointerException
 at com.example.demo.DemoApplication.myTestMethod(DemoApplication.java:7)
 at...

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.

The better way to do it will be like follows.


  if (theStringIknow.equals(someString)) {
   System.out.println("Same same");
  }

In that case, you are always invoking the equals method of a String that you are pretty sure it exists. Usually, it could be a constant or a new String object.

If you are not really sure either of them exists, so you better to check for null for the String that you are trying to invoke the equals method of.



 if (someString != null && someString .equals(someOtherString)) {
  System.out.println("Same same");
 }


Happy coding!






Comments

Popular posts from this blog

Install Docker on Windows 11 with WSL Ubuntu 22.04

This is to install Docker within Ubuntu WSL without using the Windows Docker application. Follow the below steps. Install Ubuntu 22.04 WSL 1. Enable Windows Subsystem for Linux and Virtual Machine platform Go to Control Panel -> Programs -> Programs and Features -> Turn Windows features on or off 2. Switch to WSL 2 Open Powershell and type in the below command. wsl --set-default-version 2 If you don't have WSL 2, download the latest WSL 2 package and install it.  3. Install Ubuntu Open Microsoft Store and search for Ubuntu. Select the version you intend to install. I'd use the latest LTS version Ubuntu 22.04. Click on the Get button. It will take a couple of minutes to download and install. 4. Open up the installed Ubuntu version that was installed. If you get an error like the below image, make sure to install the WSL2 Kernel update .  If it's an older Ubuntu version the error message would be something like the image below. Error: WSL 2 requires an update to its

How to fix SSLHandshakeException PKIX path building failed in Java

TL ; DR 1. Extract the public certificate of the website/API that you are trying to connect from your Java application. Steps are mentioned in this post 2. Use the Java keytool to install the extracted certificate into the "cacerts" file (Trust store) keytool -import -trustcacerts -alias <domain name> -file <public certificate>.cert -keystore /path_to_java_home/jre/lib/security/cacerts -storepass changeit 3. Restart your Java application Exception A typical exception stack trace would look like below. javax.net.ssl. SSLHandshakeException : sun.security.validator.ValidatorException: PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) at sun.security.ssl.Handshake

How to set terminal title in Ubuntu 18.04 LTS

In older Ubuntu versions, you could have just right-clicked on the Ubuntu Terminal window's title bar and set any title you would like. But unfortunately after Ubuntu 18.04 LTS this feature is gone. I used to love this feature because I'm multiple tabs in the single terminal window kind of a guy. I usually like to work in multiple named terminal tabs like below. By default, in newer Ubuntu version, it is showing just the current directory. Let's see how we can do this. Ubuntu prompt In ubuntu's Bash, there's an environment variable $PS1 which is responsible for the details that the command line prompts. You'll be able to echo this and see what's inside it. If I echo it it will print something like this. echo $PS1 \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ If you really want to understand what this means, you can refer this page .  Updating the termina