Wednesday, January 15, 2014

What is that method parameter type followed by three dots such as "String... args" or "E... elements"?

It is called var-args added to Java in Java 1.5. It can only be used as the last argument parameter in a method. It is treated as an array, that is "int... values" will be treated as "int[] values", however the number of arguments passed to the method can vary each time the method is called. You can actually pass an int[] object of any length to the method at the time of calling the method. Or you can omit this parameter entirely if you have no value to pass to the method.

public class VarargsTest {
      public void test (String name, int... values) {
            System.out.println("Number of values: " + values.length);
            System.out.print(name + ": ");

            for (int value : values) {
                  System.out.print (value + ", ");
            }
            System.out.println("");
      }

      public static void main(String[] args) {
            VarargsTest vt = new VarargsTest();
            vt.test ("Person ID", 88, 192, 5533, 4432);

            //passing in an in[] object
            int[] values = {33, 65, 67, 69, 80, 88, 59, 90};
            vt.test ("Book #", values);

            //omitting the parameter
            vt.test("Returned books: ");
      }
}

References:
1. VarArgs in Java Tutorial for Beginners
2. Varargs In Java: Variable Argument Method In Java 5

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment