Question

Can any one tell the use of varargs method in java?

And, I have requirement that in html there are too many fields so can we use vararg method for null validation, if possible please tell me how ?

Was it helpful?

Solution

Here is a demo:

public void myVarargsMethod(MyObject... objects) {
    if (objects.length() == 0) {

         // No parameters passed to the method...

    } else {

         for(MyObject mo : objects) {
            if (mo==null) {
                // Process null value ...
            } else {
                // Process MyObject instance...
            }
         }

    }
}

OTHER TIPS

Sometimes you wish you could create methods with an arbitrary number of arguments. A classic example is a logging function which takes templates with an arbitrary number of placeholders:

 logger.log("%s: %s" , "Input", "Hello world");
 logger.log("%s: %s %s", "Input", "Hello", "world");

That shows log() being called with 3 and 4 parameters, and you could support that by writing a number of versions:

 void log(String pattern, String val1, String val2) { ... }
 void log(String pattern, String val1, String val2, String val3) { ... }

... and in early versions of Java, people did that, but clearly you can't go on adding ever-longer versions, and at some point you'd say "OK, this is getting silly", and provide:

 void log(String pattern, String[] values) { ... }

... to be called thus:

 logger.log("%s: %s", new String[] { "Hello", "world" });

Varargs provides a syntax to let you allow the caller to supply as many arguments as they like.

 void log(String pattern, String... values) {
       // implementation sees values as a String[]
 }

... and with this version, the caller doesn't need to explicitly create an array. It can be called with as many trailing arguments as you like:

 logger.log("%s %s %s %s %s %s %s", 
       "The", "quality", "of", "mercy", "is", "not", "strained.");

I don't see any particular affinity between varargs and HTML field validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top