«Back to Home

Core Java

Topics

Variable Argument In Java

Variable Argument
 
In Java, the variable argument (varrags) permits the method to accept zero or multiple arguments. Before variable argument, we either use overloaded method or receive an array as the method parameter but it was not considered good because it creates the maintenance problem. If we don't know how many arguments, we will have to pass in the method then variable argument is the better approach.
 
We don't have to provide overloaded methods. Thus, less coding is involved.
 
Syntax

The variable argument uses ellipsis i.e. three dots after the data type.
 
return_type method_name(data_type... variableName){}
 
Rules for Variable Argument

While using the variable argument, we must follow some rules otherwise the program code won't compile. The rules are,
  • Only one variable argument can be included in the method.

  • Variable argument should be the last argument.
Examples of variable argument that fails to compile are,
 
void method(String... x, int... y){}
 
void method(int... x, String y){}
 
Let’s see an example, given below.
 
Code
  1. public class VariableArgs {  
  2.     static void print(String...values) {  
  3.         System.out.println("Print method called.. ");  
  4.     }  
  5.     public static void main(String args[]) {  
  6.         print();  
  7.         print("I""am""Variable""Argument");  
  8.     }  
  9. }  
60
Output

61

Let’s see another example, given below.
 
Code
  1. public class VariableArgs {  
  2.     static void print(String...values) {  
  3.         System.out.println("Print method called.. ");  
  4.         for (String s: values) {  
  5.             System.out.println(s);  
  6.         }  
  7.     }  
  8.     public static void main(String args[]) {  
  9.         print();  
  10.         print("hello");  
  11.         print("I""am""Variable""Argument");  
  12.     }  
  13. }  
62

Output

63

Let’s see another example, given below.
 
Code
  1. public class VariableArgs {  
  2.     static void print(int n, String...values) {  
  3.         System.out.println("Number is :" + n);  
  4.         for (String s: values) {  
  5.             System.out.println(s);  
  6.         }  
  7.     }  
  8.     public static void main(String args[]) {  
  9.         print(1"hello");  
  10.         print(2"I""am""Variable""Argument");  
  11.     }  
  12. }  
64
 
Output

65

Summary

Thus, we learnt that the variable argument (varrags) permits the method to accept zero or multiple arguments and also learnt its important rules in Java.