[Simple Java] Java Variable Parameter example, simplejava
What is a Java Variable Parameter?
Variable parameters are a feature introduced by Java 1.5. They allow a method to accept any number of parameters.
Package simplejava; public class Q25 {public static void print (String... s) {for (String a: s) System. out. println (a);} public static void main (String [] args) {print ("a"); print ("a", "B "); print ("a", "B", "c ");}}
How variable parameters work
When a variable parameter is used, an array is created first. The array length is the number of parameters, the parameter is uploaded to the array, and the array is finally passed to the method.
When to use variable parameters
Just like its name, the variable parameter mechanism is very useful when a method needs to process any number of parameters. A good example is the String in JDK. format (String format, Object... args) method. This method can receive any number of parameters for string formatting. Therefore, it can be implemented using a variable parameter mechanism.
Http://www.programcreek.com/2014/01/java-varargs-examples/.