java checking for null

java checking for null

To check if a reference variable in Java is null, you can use the == operator and compare the variable to null.

Here's an example of how to use the == operator to check if a reference variable is null:

refer ‮ual:ot‬tturi.com
public class Main {
  public static void main(String[] args) {
    String str = null;
    if (str == null) {
      // str is null
    } else {
      // str is not null
    }
  }
}

In this example, the if statement compares the value of the str variable to null using the == operator. If the value of str is null, the if block is executed. If the value of str is not null, the else block is executed.

You can also use the Objects.isNull method of the java.util.Objects class to check if a reference variable is null. This method takes a reference variable as an argument and returns true if the value is null, and false if the value is not null.

Here's an example of how to use the Objects.isNull method to check if a reference variable is null:

import java.util.Objects;

public class Main {
  public static void main(String[] args) {
    String str = null;
    if (Objects.isNull(str)) {
      // str is null
    } else {
      // str is not null
    }
  }
}

Note that you should not use the != operator to check if a variable is null.

Created Time:2017-11-03 00:14:49  Author:lautturi