How to check NULL in Java?

Can someone please let me know the standard way to check whether an object is NULL? I'm new to Java. Really appreciate your help.

Comments

  • Try

    if(object_name.equals(null))
    {
    do something
    }
  • [code]
    if(obj == null)
    [/code]

  • we can use both == operator or equals operator to check whether an object is null or not.
    Object obj ;
    Here we have created a reference for Object class. So the value will be null.
    if(obj == null)
    System.out.println("obj is not assigned");
    else
    System.out.println("obj is assigned. Carry on");

    0r

    if(obj.equals(null))
    System.out.println("obj is not assigned");
    else
    System.out.println("obj is assigned. Carry on");

  • You can use either "==" or "equals()" method of String class to ckeck whether string is null or not

    Example:

    String a=null;

    Method1:
    if(a==null)
    System.out.println("String is null");
    else
    System.out.println("String is not null");

    Method 2:
    String b=null;
    if(a.equals(b))
    System.out.println("String is null");
    else
    System.out.println("String is not null");

    For more Details Refer following link:
    java.meritcampus.com/t/226/Equals-vs------string-comparison?tc=mm210

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories