Google+

187. varargs parameter must be used only once in a method







Pre-requisite -


While using varargs concept, the Java Compiler will throw compile time errors if we use it wrongly. According to Java, when you use varargs parameter more than once in any method, Java will throw compile time error. So use varargs parameter only once in any method.

Example for varargs which throws Compile time error -

void sum(int ... var1, int ... var2)
{
        //Method's code
}

As this example is using more than one varargs parameter in the method, Java will throw compile time errors when compiled.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, open the Java Project  'Project 21' created in previous post,  create a Java Class 'VarargsError2Demo' as shown below -


 2. Crete a method sum( ) containing more than one varargs parameter as shown below  -



3. View the error and observe that an error is displayed as shown below -


Though the last two parameters in the above method sum( ) are varargs parameters, compiler is throwing error for last but one varargs parameter. Hence we cant have more than one varargs parameters in any method.

4. Now resolve that error by removing the last varargs parameter and observe that the error got resolved as shown below -



Hence we cant use more than one varargs parameters in a method.





Please comment below to feedback or ask questions.

Creating more than one Class in a single Java Class file will be explained in the next post.













No comments:

Blog Index