Reputation:
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
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
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
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:
site
really is nullIf you want to test for null/empty/empty-or-whitespace there are various third-party libraries which have that functionality.
Upvotes: 13
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
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
Reputation: 1231
Are you sure that the string is being assigned null
the value, and not "null"
the string?
Upvotes: 0