What are Variable Arguments in Java - onlyxcodes

Monday, 15 May 2023

What are Variable Arguments in Java

Variable arguments in Java, frequently referred to as varargs, enable a method to accept an arbitrary number of arguments of the same data type.


This means that you can supply a method with a variable number of parameters, which is beneficial if you are unsure of the exact number of arguments to supply.


variable arguments in java

What are Varargs?

Java's Varargs feature enables methods to take a variable number of arguments. As long as they are all of the same data types, a method can accept a varying number of parameters each time it is called. 


The method signature's last parameter's data type is followed by an ellipsis (...), which designates that the following argument is a variable.


Syntax:


return_type method_name(data_type... variableName)
{
	//method body
}

How Does Varargs Work?

Java automatically makes an array to retain the arguments when you send them to a method that uses varargs. The array's data type is the same as the varargs parameter's data type. 


The arguments will be stored in an int array if the varargs parameter, for instance, has the type int.


It's crucial to remember that varargs can only be applied to a method signature's final parameter. This is due to the fact that the method can receive any number of varargs arguments, thus it must be the last parameter in the method signature.


Using Varargs in Java

Let's look at using varargs in Java now that we understand what they are and how they function.


Simply define the argument in the method signature using the ellipsis notation to use varargs. 


For instance:


The method sum in the example below accepts a numbers of integer varargs input. After adding up all the numbers supplied, the procedure provides the outcome.


public static int sum(int... numbers) 
{ 
	int result = 0;
  
	for (int number : numbers) 
	{
		result += number;
	}
	
	return result;
}

The sum() method can be invoked in a number of different ways:


int result1 = sum(1, 2, 3, 4, 5);
int result2 = sum(1, 2, 3);
int result3 = sum();

Five arguments are passed to the sum function in the first call to it. Three arguments are passed in during the second call, but none are passed during the third.


Full Code,


class VarargsExample
{
	public static void main(String args[])
	{
		int result1 = sum(1, 2, 3, 4, 5);
		int result2 = sum(1, 2, 3);
		int result3 = sum();
		
		System.out.println(result1);
		System.out.println(result2);
		System.out.println(result3);
	}
	
	public static int sum(int... numbers) 
	{
		int result = 0;
		
		for (int number : numbers) 
		{
			result += number;
		}
		
		return result;
	}

}

Output:


15
6
0

Varargs with Other Parameters

Varargs may also be used in combination with other arguments. In these circumstances, the varargs parameter must always be the method signature's last parameter. 


For instance:


The method printValues in the example below requires two inputs: a String separator and an integer varargs parameter named values. The procedure then outputs the separator string between each of the values that were supplied.


public static void printValues(String separator, int... values) 
{
	for (int value : values) 
	{
		System.out.print(value + separator);
	}
}

The printValues method can be invoked in a number of different ways:


printValues(",", 1, 2, 3, 4, 5);
printValues(":", 1, 2, 3);
printValues("", 1, 2, 3);

The first call involves passing five integer inputs and a comma as separators. 


We pass three integer arguments and a colon as the separator in the second call. 


The third call involves passing three integer arguments together with an empty string as a separator. 


Full Code,


class VarargsExample
{
	public static void main(String args[])
	{
		printValues(",", 1, 2, 3, 4, 5);
		printValues(":", 1, 2, 3);
		printValues("", 1, 2, 3);

	}
	
	public static void printValues(String separator, int... values) 
	{
		for (int value : values) 
		{
			System.out.print(value + separator);
		}
	}
}

Output:


1,2,3,4,5,1:2:3:123

Benefits of Using Varargs

The advantages of using varargs in Java are numerous. Among these advantages are:


Code reusability:


Instead of writing several methods, you may use one method to accept a variety of arguments, which can save you time and effort.


Flexibility:


Any type of argument can be used with varargs, making it simple to design methods that can take a variable number of arguments of any kind.


Clarity:


As it allows you to pass a variable number of arguments without having to explicitly describe each one, using varargs can improve the readability and clarity of your code.


How Varargs Works in Java Behind the Scene?

Java creates an array to keep the parameters supplied to a varargs function when it is called in the background. The array's size is determined by the number of arguments passed. Then, the method receives the array as a parameter.


Consider the following approach, for instance:


Java builds an array [1, 2, 3] and gives it to the method as the numbers parameter if we call this method with printNumbers(1, 2, 3).


public static void printNumbers(int... numbers) 
{
	for (int num : numbers) 
	{
        System.out.println(num);
	}
}

Full Code,


class VarargsExample
{
	public static void main(String args[])
	{
		printNumbers(1, 2, 3);
	}
	
	public static void printNumbers(int... numbers) 
	{
		for (int num : numbers) 
		{
			System.out.println(num);
		}
	}
}

Output:


1
2
3

Varargs can also be combined with other parameters. 


For instance:


If we use printInfo("Australia", 1, 2, 3), Java will build an array [1, 2, 3] and provide it as the numbers parameter to the function, while the name parameter will receive the value "Australia".


public static void printInfo(String name, int... numbers) 
{
	System.out.println("Country Name: " + name);
		
	for (int num : numbers) 
	{
		System.out.println(num);
	}
}

Full Code,


class VarargsExample
{
	public static void main(String args[])
	{
		printInfo("Australia",1, 2, 3);
	}
	
	public static void printInfo(String name, int... numbers) 
	{
		System.out.println("Country Name: " + name);
		
		for (int num : numbers) 
		{
			System.out.println(num);
		}
	}

}

Output:


Country Name: Australia
1
2
3

Overloading Varargs Methods Example in Java

Here is an illustration of Java overloading for varargs methods:


public class VarargsExample 
{
   public static void main(String[] args) 
   {
		VarargsExample ex = new VarargsExample();
		  
		// calling the method with one argument
		ex.printValues(1);
		  
		// calling the method with two arguments
		ex.printValues(2, 3);
		  
		// calling the method with three arguments
		ex.printValues(4, 5, 6);
		  
		// calling the method with an array argument
		int[] array = {7, 8, 9};
		ex.printValues(array);
   }
   
   // method with one argument
	public void printValues(int a) 
	{
		System.out.println(a);
	}
   
	// method with two arguments
	public void printValues(int a, int b) 
	{
		System.out.println(a + " " + b);
	}
   
	// method with three arguments
	public void printValues(int a, int b, int c) 
	{
		System.out.println(a + " " + b + " " + c);
	}
   
	// method with a variable number of arguments
	public void printValues(int... values) 
	{
		for (int i : values) 
		{
			System.out.print(i + " ");
		}
		
      System.out.println();
   }
}

Output:


1
2 3
4 5 6
7 8 9

Explanation:


The class VarargsExample in the example above has four methods that are overloaded according to the number of arguments they receive. 


The last method, printValues(int... values), allows a variable number of arguments (i.e., a varargs parameter), whereas the first three methods accept a set number of parameters.


We make a VarargsExample class instance in the main method and call each of these methods with various arguments. 


The Java compiler automatically turns the arguments into an array when we call the printValues method with a variable number of arguments. This array is then supplied to the method.


We send an array of numbers as a parameter to printValues in the last call. An array can also be passed as input to the varargs parameter, and each entry will be considered as a single argument.


Point to Remember While using Varargs in Java

The following considerations should be made while using varargs in Java:


The last argument in a method's signature should be varargs.


Varargs can only be applied to one method argument.


Varargs can receive either an array or a single element as input. Java automatically creates an array from the given values when invoking a varargs operation.


Java automatically creates an array from the given values when invoking a varargs operation.


Best Practices for Using Varargs

Varargs can be helpful, but it's crucial to utilize them properly to prevent any code mistakes. The following are some recommended methods for using Java's varargs:


Varargs should only be used when it makes sense to do so, even though they can be helpful. Varargs can make your code difficult to read and manage if you use them too frequently.


Keep varargs separate from other arguments: In order to prevent such mistakes, it is often a good practice to use varargs as the method signature's last parameter.


Instead, think about using a collection: Varargs may occasionally be preferable than using a collection (like an ArrayList). This is especially true if you need to use the arguments in more complex processes.


Conclusion:

Varargs are a potent Java utility that can speed up and improve the efficiency of your code. You can write more adaptable and easily maintainable code by adhering to standard practices and minimizing the use of varargs.


You should now have a better understanding of Java varargs and how to use them in your code.


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

Context Switching in Java Thread Example

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad