Variable Arguments in Java

Variable Arguments in Java

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 UnderstandingVarArgsOverloaded int method.No of arguments of type int: 4Overloaded String method.No of arguments of type String: 3*/ 
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist