Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Variable Arguments (Varargs) in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 326
    Comment on it

    Variable Arguments (Varargs) in Java

    • Variable Arguments (Varargs) was introduced in JDK 5.
    • Varargs as the name suggest allows a function to be called with different number of arguments as per the requirement.
    • The syntax of Varargs:
    returntype methodname(datatype ...a)
    • A method can have normal parameters and variable length parameters together but the only requirement is that varargs parameter should be written last in the parameter list of the method declaration.Example:
    int nums(int a, float b, double  c)

    Example of Variable Arguments (Varargs) in Java:

    class Demo
    {
        // Takes string as a argument followed by varargs
        static void fun2(String str, int ...a)
        {
            System.out.println("String: " + str);
            System.out.println("Number of arguments is: "+ a.length);
     
            // for each loop to display contents of a
            for (int i: a)
                System.out.print(i + " ");
     
            System.out.println();
        }
     
        public static void main(String args[])
        {
            // Calling fun2() with different parameter
            fun2("Test1", 100, 200);   
            fun2("Test2", 1, 2, 3, 4, 5);
            fun2("Test3");
        }
    }

    Output:

    String: Test1
    Number of arguments is: 2
    100 200 
    String: Test2
    Number of arguments is: 5
    1 2 3 4 5 
    String: Test3
    Number of arguments is: 0

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: