tags:

views:

117

answers:

5
+1  Q: 

null value in java

hello, i am getting an string from using swing and i need to validate if it is not null i use this code

if(site.equals(null)) {
    System.out.println("null");
} else  {
    System.out.println("notnull");
}

it always show "notnull" if there is null also

+8  A: 

To test for actual nullity, use == like this:

if (site == null)

Or indeed the conditional operator, for situations like the one shown:

System.out.println(site == null ? "null" : "notnull");

Note that a null reference is not the same as an empty string. How do you want an empty string to behave? If you truly had a null reference, then your current code would have thrown a NullPointerException.

The simplest way for testing an empty string is with the isEmpty method:

System.out.println(site.isEmpty() ? "empty" : "not empty");

Note:

  • This will throw an exception if site really is null
  • This will treat whitespace as irrelevant

If you want to test for null/empty/empty-or-whitespace there are various third-party libraries which have that functionality.

Jon Skeet
same thing is happening it says not null i used trim() also
Ram
Maybe your string isnt null?
Visage
i need to neglight the empty string the process should not start for empty string
Ram
A: 

Are you sure that the string is being assigned null the value, and not "null" the string?

Alex Larzelere
Any reason why I was downvoted? That's a perfectly valid response. Considering he has no control over the string he's being passed, someone else could have made that error.
Alex Larzelere
+4  A: 

The problem is probably related to the textbox you are using will always return a string, just an empty one.

Change your check to the following and see if it works.

if(site.equals(""))

Note that this won't stop them from simply putting a space in though. you would need to trim the input first.

Matt
it worked yar thank u a lot ......
Ram
You should use String.isEmpty() instead of comparing it to "".
Steve Kuo
Good job of looking past what the questioner was asking and figuring out what he needed--wish I could give +2.
Bill K
actually a better idiom is `"".equalsIgnoreCase(site);` it avoids the null pointer exception if site is null and IngnoreCase is faster when site != ""
fuzzy lollipop
A: 

The String.equals() method only returns true if the argument is not null, and then only if the argument is an identical String. See the documentation.

You should initially be using a direct comparison to find out if either string is null, before you do a further check for equivalence.

   if (site == null) ...
Graham Borland
A: 

Have you tried stringutils class? Here is the link --> http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html

You can check for string "nullness" and "emptiness" in a null-safe way and act accordingly

Suji