Google+

186. varargs parameter must be the last parameter in the 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 in any method, you must make sure that varargs parameter must be the last parameter.

Example for varargs which throws Compile time error -

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

As this example is using varargs parameter in the first place of all the parameters of the method, Java will throw compile time errors when compiled.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Project  'Project 21' as shown below -


2. Create a Class 'VarargsError1Demo' as shown below -


3. Create a static method sum( ) by providing varargs parameter as first parameter in the method as shown below -


4. Select 'Change project compliance and JRE to 1.5' option in the displayed error message as shown below -


5. Observe that a compile time error with message 'The variable argument type int of the method sum must be the last parameter' is displayed as shown below -


6. Now move the varargs parameter to the last as shown below and observe that the error got resolved -



Hence, varargs parameter must be the last parameter in any method.






Please comment below to feedback or ask questions.

varargs parameter must be used only once in a method  will be explained in the next post.




 

No comments: