Checking if condition for 'null'

99,887

Solution 1

If you want to check is a String is null, you use

if (s == null)

If you want to check if a string is the empty string, you use

if (s.equals(""))

or

if (s.length() == 0)

or

if (s.isEmpty())

An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.

Solution 2

To check both "is not null" and "is not empty" on a String, use the static

TextUtils.isEmpty(stringVariableToTest)

Solution 3

It looks like you want to check wether a String is empty or not.

if (string.isEmpty())

You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().

Solution 4

When you are working on String always use .equals.

equals() function is a method of Object class which should be overridden by programmer.

If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))

Solution 5

You can use:

we can check if a string is empty in 2 ways:

  • if(s != null && s.length() == 0)
  • if(("").equals(s))
Share:
99,887
Sjk
Author by

Sjk

Updated on March 01, 2020

Comments

  • Sjk
    Sjk about 4 years

    I have a doubt regarding checking null condition.For eg :

    if(some conditon)
    value1= value;  //value1 is string type
    else 
    value1= "";
    

    Similarly some 4 other string value has similar condition. What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part. i did it like this

    if(value1 == null)
    {
    }
    

    but the pgm control didnot entered the loop eventhough value1="". then i tried

    if(value1 ==""){
    } 
    

    this also didnt worked.

    Cant we check null and "" value as same?? can anyone help me??