Mazzy
Mazzy

Reputation: 14189

Check if a html input field is empty in java

I'm creating a web application by using java ee. I have a doubt. To check correctly if a text field is NOT empty is right to do this check?

    if(home_number != null || !(home_number.equals("")))
    {

    }

There are also .isEmpty() functin and lenght() > 0 to check if a string is NOT EMPTY. Which is the best way?

Upvotes: 0

Views: 3491

Answers (4)

earthmover
earthmover

Reputation: 4525

You can check if input-field is not empty using .isEmpty(), but what if the text-field is filled with spaces ???

So, I'll recommend you to use .trim() before checking for empty String :

if(str != null && !(str.trim().isEmpty())){
   // do whatever you want
}

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

The cleanest pattern, in my opinion is:

if (a != null && !a.isEmpty()) {
    // ...
}

And instead of repeating that hundreds of times, write a small static utility method to wrap this behavior, or use Google Guava's Strings.isNullOrEmpty()

Upvotes: 0

benzonico
benzonico

Reputation: 10833

In order to handle all the corner cases (what if string is null, what if it is only composed of spaces etc...) you'll probably be better off using a library that covers that properly for you like Apache commons lang and its StringUtils class: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

And therefore have a more readable code :

if(StringUtils.isNotEmpty(home_number)) { ...

Upvotes: 4

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

isEmpty is more preferable as the documentation said

Returns true if, and only if, length() is 0.

so if the length is 0 then it will return directly as true.

vs. !(home_number.equals("")

public boolean equals(Object anObject) {
if (this == anObject) {
    return true;
}
if (anObject instanceof String) {
    String anotherString = (String)anObject;
    int n = count;
    if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
                return false;
        }
        return true;
    }
}
return false;

You need to trim your string first before checking if its empty }

Upvotes: 0

Related Questions