Ram
Ram

Reputation:

null value in java

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

Upvotes: 1

Views: 6167

Answers (6)

Sanjay Jain
Sanjay Jain

Reputation: 3587

If it was null then it already gave you null pointer exception.Because you are invoking a method on null object. So It is better you use

if(site==null)

And for confirmation try this

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

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

This will print the value of site string.

Upvotes: 1

Suji
Suji

Reputation: 497

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 13

Graham Borland
Graham Borland

Reputation: 60681

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) ...

Upvotes: 0

Matt
Matt

Reputation: 2815

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.

Upvotes: 6

Alex Larzelere
Alex Larzelere

Reputation: 1231

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

Upvotes: 0

Related Questions