-4

I'm new in java programming. Now I have a problem when I have String variable equals to null. When I check condition on that String it error :

Exception in thread "main" java.lang.NullPointerException.

This is my code :

public class Test {
    static String a=null;
    public static void main(String[] args) {
        if(a.equals(null)){
            System.out.println("Null");
        }
    }
}
0

4 Answers 4

4

Instead of a.equals(null) you should be doing a == null.

if(a == null) {
    System.out.println("Null");
}

Alternatively, you can use the StringUtils to check if String is null or empty by doing:

if(StringUtils.isEmpty(a)) {
    System.out.println("Null");
}
Sign up to request clarification or add additional context in comments.

6 Comments

Why i cannot use equals() method?
Because if a itself is null, it will be null.equals() and it does not hold good. You can't invoke a method on a null object.
@user2004685: Well, on a null reference. There's no such thing as a null object. It's worth keeping the distinction between variables, references and objects very clear.
@user2004685 i cannot use StringUtils.isEmpty() method. why?
@Huo Chhunleng, you need to add org.apache.commons.lang3 dependency to your project. If you are using maven, then choose it here
|
2

If there is a potential for both references to be null, you can use

Objects.equals(a, b)

Comments

2

Check with == or != like:

if(a!=null){
    System.out.println("is not Null");
}

5 Comments

Why i cannot use equals() method?
Better in practice , Instead of using If(a!= null) you should use if(null!=a)
@ManthanB: No, that's a terrible idea: a) it's no safer; b) it's less readable. These "Yoda conditions" may make sense in some languages where the type of the condition in an if statement doesn't have to be a Boolean type, but it makes no sense in Java for situations like this.
It's not "better" to reverse the comparison, 'null != a' vs. 'a != null', because both expressions are exactly equivalent. Equality and inequality are symmetric. If anything, the reversed expression is worse, because everyone recognizes it as reversed, which slows down mental processing of the construct. There is no "practice" to the reversal; it just makes code look worse.
0

If you want to check for null

if(a == null){
  System.out.println("I am null");
}

If you want to check for empty or blank String

if(a != null && a.length() == 0){
  System.out.println("I am an empty String");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.