dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Variable Arguments in Java

Learn more about how to work with variable arguments in Java.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Moving away from the age old way of fixed arguments, Java supports variable arguments. The code sample below illustrates variable arguments.

If the method has multiple arguments, it is mandatory to have only the last argument as the variable argument.

public class UnderstandingVarArgs
{
   public static void main(String args[])
   {
      UnderstandingVarArgs understandingVarArgs = new UnderstandingVarArgs();
      understandingVarArgs.proceed(5, 6, 7, 4);
      understandingVarArgs.proceed("Hello", " my", " name");
   }
   
   private void proceed(int... varArg)
   {
      System.out.println("Overloaded int method.");
      System.out.println("No of arguments of type int: " + varArg.length);
   }

   private void proceed(String... varArg)
   {
      System.out.println("Overloaded String method.");
      System.out.println("No of arguments of type String: " + varArg.length);
   }
}

/*

Expected output:

[root@mypc]# java UnderstandingVarArgs
Overloaded int method.
No of arguments of type int: 4
Overloaded String method.
No of arguments of type String: 3

*/ 

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date