Explain about Varargs in java?


A method can accept a variable number of parameters thanks to a Java feature called variable arguments, or varargs. This can be helpful for methods that need to be able to manage an unknown or variable number of inputs.

We had two ways to handle methods that needed to take a variable number of arguments prior to introduction of varargs in Java 5. One way was to use overloaded methods. The method has to be developed in numerous iterations, each with a different number of arguments.

If the process had many arguments, it might become complicated and challenging to maintain.

Syntax of Varargs

Internally, a single-dimension array is used to implement the varargs method. This indicates that the varargs method's arguments are kept in an array and that each argument's index can be used to access it. A varargs parameter can be specified by using the three periods or dots (...).

public static void happy(int ... a) 
{
   // method body
}

With this approach, the compiler is informed that fun() may be called with 0–n or more parameters. Consequently, an implicitly specified in this case as an array of type int[].

Example 1

display()

This code defines a class named VarargsInstance with a method called display that can take a variable number of string arguments. In the main function, the display method is called twice - once without any arguments and once with four string arguments. When called, the method prints the message.

Algorithm

  • Step 1: Create a class called VarargsInstance.

  • Step 2: Define a static method called display(). This method takes a variable number of String arguments.

  • Step 3: Inside the display() method, print the following message to the console: "The display method has been called".

  • Step 4: Create a main method.

  • Step 5: In the main method, call the display() method once with zero arguments.

  • Step 6: Call the display() method again with four arguments.

  • Step 7: Run the program.

Example

public class VarargsInstance{  
   
 public static void display(String... values){  
  System.out.println("The display method has been called ");  
 }  
  
 public static void main(String args[]){  
  
 display();//zero argument   
 display("my","name","is","tutorialspoint");//four arguments  
 }   
}  

Output

The display method has been called 
The display method has been called

Example 2

happy()

This code defines a class named Example1 with a method happy() that can take a flexible number of integer arguments. Inside this method, it displays the count of arguments and lists the arguments using a loop. In the main part, it demonstrates calling the happy() method with different numbers of arguments, producing output that shows the counts and values of the provided arguments.

Algorithm

  • Step 1: Create a class called Example1.

  • Step 2: Define a static method called happy(). This method takes a variable number of int arguments.

  • Step 3: Inside the happy() method, do the following:

    • Print this to the console: "Count of arguments: " + a.length.

    • Print the contents of the array to the console by iterating through the a variable via a for each loop.

  • Step 4: Create a main method.

  • Step 5: In the main method, do the following:

    • Call the happy() method once with one argument, 250.

    • Call the happy() method again with four arguments, 20, 30, 40, and 50.

    • Call the happy() method again with zero arguments.

  • Step 6: Run the program.

Example

public class Example1 {

	static void happy(int... a)
	{
		System.out.println("Count of arguments: "
						+ a.length);

		// employing 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 the varargs method with various number of parameters
	
		happy(250);
		
		// four parameters
		happy(20, 30, 40, 50);
		
		// no parameter
		happy();
	}
}

Output

Count of arguments: 1
250 
Count of arguments: 4
20 30 40 50 
Count of arguments: 0

Example 3

display()

In this code, there's a class named VarargsInstance2 with a method display() that can take a variable number of string arguments. When the method is called, it prints "display method called" and then lists out each provided argument on separate lines. In the main part, the display() method is demonstrated by calling it with different numbers of arguments, generating the displayed output as shown.

Algorithm

  • Step 1: Create a class called VarargsInstance2.

  • Step 2: Define a static method called display(). This method takes a variable number of String arguments.

  • Step 3: Inside the display() method, do the following:

    • Print the following message to the console: "display method called".

    • Employ a for each loop to iterate over the values variable and print the contents of the array to the console.

  • Step 4: Create a main method.

  • Step 5: Within the main method, perform the following:

    • Call the display() method once with zero arguments.

    • Call the display() method again with one argument, "hey".

    • Call the display() method again with four arguments, "welcome", "all", "to", and "Tutorialspoint".

  • Step 6: Run the program

Example

public class VarargsInstance2{  
   
 static void display(String... values){  
  System.out.println("display method called ");  
  for(String s:values){  
   System.out.println(s);  
  }  
 }  
  
 public static void main(String args[]){  
  
 display();//zero argument   
 display("hey");//one argument   
 display("welcome","all","to","Tutorialspoint");//four arguments  
 }   
}  

Output

display method called 
display method called 
hey
display method called 
welcome
all
to
Tutorialspoint

Example 4

for()

With the method joy(), which accepts a string and a flexible number of integer arguments, this code defines a class named Tutorialspoint. When the method is called, it displays the given string, the count of provided arguments, and then lists the integer arguments using a loop. In the main part, the joy() method is demonstrated by calling it with different combinations of a string and integers, producing the displayed output as shown.

Algorithm

  • Step 1: Define a static method called joy(). This method takes a String argument and a variable number of int arguments.

  • Step 2: Inside the joy() method, do the following:

    • Print thia to the console: "String: " + str.

    • Print thia to the console: "count of arguments is: " + b.length.

    • Use a for each loop to iterate over the b variable and print the contents of the array to the console.

  • Step 3: Create a main method.

  • Step 4: Within the main method, do the following:

    • Call the joy() method once with the string "TLP" and the two integers 250 and 350.

    • Call the joy() method again with the string "Example" and the five integers 20, 30, 40, 50, and 60.

    • Call the joy() method again with the string "for students" and no integers.

  • Step 5: Run the program.

Example

public class Tutorialspoint{

	static void joy(String str, int... b)
	{
		System.out.println("String: " + str);
		System.out.println("count of arguments is: "
						+ b.length);

		// employing for each loop to display contents of a
		for (int i : b)
			System.out.print(i + " ");

		System.out.println();
	}

	public static void main(String args[])
	{
		// Calling joy() with different parameter
		joy("TLP", 250, 350);
		joy("Example", 20, 30, 40, 50, 60);
		joy("for students");
	}
}

Output

String: TLP
count of arguments is: 2
250 350 
String: Example
count of arguments is: 5
20 30 40 50 60 
String: for students
count of arguments is: 0

Conclusion

Vararg Methods can be intentionally diversified, although this diversification might potentially introduce uncertainty. In the era predating JDK 5, there existed two avenues to manage arguments of variable lengths: overloading or utilization of an array argument. It's important to note that within a method, only a solitary variable argument is permissible. Furthermore, it's imperative that the variable argument (Varargs) retains its position as the ultimate argument.

Updated on: 29-Aug-2023

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements