4

Hi I have many fields that I need to validate for the null and empty i.e ""

If I have to validate 5 strings then here is the code.

string.equals("") || string1.equals("") || string2.equals("") || string3.equals("") || string4.equals("")
 || 
string.equals(null) || string1.equals(null) || string2.equals(null) || string3.equals(null) || string4.equals(null)

then it looks odd. If there are about 10 strings then more ugly.

Please tell me the best practice to do it.

5
  • 3
    10 question has been asked by you, none of answer is worthy to you?. Commented Apr 1, 2011 at 13:09
  • 1
    Accept some of your answers, it's the green tick on the left by the up and down arrows. Commented Apr 1, 2011 at 13:12
  • you post "worthy" comment as you yourself worthy for me to accept any answer. :) Sure I am going to do it. Commented Apr 1, 2011 at 13:31
  • you can only mark one answer as 'green tick' , you removed it ;-) Commented Apr 1, 2011 at 13:44
  • @Blundell oh Sorry i don't know about "one answer" limitation. Anyhow I make your answer up(useful). if my question is useful or clear to you in any case then you can give it an up. :) Commented Apr 1, 2011 at 13:54

9 Answers 9

11

You should write a method such as below;;

public static boolean isNullOrEmpty(String... strArr) {
       for (String st : strArr) {
            if  (st==null || st.equals(""))
               return true;

       } 
       return false;
}



boolean result = isNullOrEmpty(string1,strin2,string3,string4,string5);
Sign up to request clarification or add additional context in comments.

3 Comments

+1: With varargs, you don't need the new String[] { ;) Perhaps isNullOrEmpty is better
@Peter Lawrew, applied recommended changes. :)
Just need to add a ')' to the if statement. ;)
2

Not sure about best practice, but you could tidy up your code:

String[] inputs = new String[5];
inputs[0] = "whatever";

private boolean stringValidate(String[] inputs){
      for(int i=0; i < inputs.size(); i++){
           String currentString = inputs[i];
           if(currentString == null || currentString.equals(""){
               return false; // validation failed
           }
      }
      return true; // Validation passed
}

You could probably use a List make it even nicer.

EDIT

Yes as peter says using VarArgs (which I should do more often!):

private boolean stringValidate(String... inputs) {
      for (String currentString  : inputs) {
          if(currentString == null || currentString.equals(""){
               return false; // validation failed
           }
      }
      return true; // Validation passed
   }

Called like this:

stringValidate("foo", "bar", "bar");

1 Comment

Using varargs and the foreach loop would make this nicer. ;)
2

At least you can optimize:

string1.equals("") || string1.equals(null)

to

StringUtils.isBlank(string1);

StringUtils: http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

1 Comment

please tell me about StringUtils. is this a system class or any framework class?
1

string.equals(null) would never work, since if string was null, you'd get an NPE. I guess you mean string == null.

Nevertheless, you could use apache commons lang's StringUtils which would reduce the check to StringUtils.isEmpty(string) || ...

Comments

1

Create a validate method to handle each one.

private boolean isValid(String parameter){
if (parameter == null || parameter.isEmpty()) return false;
return true;
}

Then you can call this method for each of your strings. Note that if you're using an earlier version of java than 1.6, you can replace the isEmpty() method with !parameter.equals("")

Comments

1

Firstly string.equals(null) is never true. is string is null this will throw a NullPointerException.

You can use string == null || string.equals("")

The problem you have is that you have many fields/variables which you want to treat in a generic fashion but you have different names. An alternative is to use an array or List

String[] strings = { .... }
boolean notAllSet = false;
for(String s: strings)
   notAllSet |= s==null || s.equals("");

Comments

0

For one thing, a best practice is to do

 "FOO".equals(myString)

instead. This reduces the chance of NPEs and makes it clearer that no mutation is going on. For a discussion of this, see here.

Also, if you really have a collection of strings to compare to, you probably want

 final Set<String> validStrings = ...

 boolean validate(final String foo) {
    return foo!=null && validStrings.contains(foo);
 }

Comments

0

When you're handling a lot of variables of the same type, you can manage them in a structure, such as an ArrayList, then create a method to do the work for you.

public static void main(String[] args){
    ArrayList<String> hold = new ArrayList<String>();
    hold.add(string);
    hold.add(string1);
    hold.add(string2);
    hold.add(string3);
    hold.add(string4);

    if( validate(hold) )
        System.out.println("No blanks, no nulls");
}

public boolean validate(ArrayList<String> hold){
     for( int x = 0; x < hold.size(); x++ ){
          if( hold.get(x).equals("") || hold.get(x).equals(null) )
                return false;
     }

     return true;
}

Comments

0

I know the question is very old, but I find StringUtils to be more suited for this.

StringUtils.isAnyEmpty(String... args)

Or

StringUtils.isAnyBlank(String... args)

Hope this helps someone!

Docs, here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.