Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate. I tried all this but that didn't work.

String COMPLETEDATE;
COMPLETEDATE = country[23];

if(country[23] == null && country[23].length() == 0) 
{
    // ...
}

if (COMPLETEDATE.equals("null")) 
{
    // ...
}

if(COMPLETEDATE== null)
{
    // ...
}

if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
    // ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:

if("constantString".equals(COMPLETEDDATE)) {
    // logic
}

But in general, your approach isn't correct.

The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.

The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.

Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.

Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...