-2

I don't want to use try block to catch the exception I just want to check null with if condition.when i try that it is giving me the null pointer exception.

public class test {
    public static void main(String[] args) {
       String name=null;
       if(name.equals(null)){
          System.out.println("null");
       }
       System.out.println("done");
    }
}
reza.cse08
  • 5,938
  • 48
  • 39
  • `equals()` is a method belonging to an object. Since you don't have an object (the reference is null) you cannot call the method, and when you try to do that, you get NullPointerException. – RaminS May 26 '16 at 13:33

1 Answers1

2

That's because you're calling name.equals(something), which requires name to be non-null.

Just use name == null instead.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243