Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Variable parameters, also known as varargs, allow you to pass a variable number of arguments to a Java method. This can be helpful when you don't know the exact number of arguments that will be passed to a method. Varargs are represented as an array in the method, and you can use them just like any other array. In this tutorial, we will cover the basics of using variable parameters in Java methods.
To define a method with variable parameters, use the ellipsis (...
) notation followed by the parameter type and name.
public static void printNumbers(int... numbers) { for (int number : numbers) { System.out.print(number + " "); } System.out.println(); }
In this example, the printNumbers
method accepts a variable number of int
parameters.
You can call a method with variable parameters by passing any number of arguments of the specified type, separated by commas.
public class Main { public static void main(String[] args) { printNumbers(1, 2, 3); printNumbers(4, 5, 6, 7, 8); } public static void printNumbers(int... numbers) { for (int number : numbers) { System.out.print(number + " "); } System.out.println(); } }
The output of this code will be:
1 2 3 4 5 6 7 8
You can also pass an array to a method with variable parameters. The array will be treated as if each element were passed as a separate argument.
public class Main { public static void main(String[] args) { int[] numbers = {1, 2, 3}; printNumbers(numbers); } public static void printNumbers(int... numbers) { for (int number : numbers) { System.out.print(number + " "); } System.out.println(); } }
The output of this code will be:
1 2 3
This tutorial introduced the basics of using variable parameters (varargs) in Java methods, including defining methods with variable parameters, calling methods with variable parameters, and passing arrays to methods with variable parameters. Varargs are a useful feature in Java that allows you to create more flexible and expressive APIs while keeping your code clean and organized.
Varargs in Java methods:
void printNumbers(int... numbers) { for (int num : numbers) { System.out.print(num + " "); } }
How to use variable parameters in Java:
void displayValues(String... values) { for (String val : values) { System.out.println(val); } }
Java methods with a variable number of parameters:
void processData(String operation, int... numbers) { // Implementation }
Java varargs and method overloading:
void printValues(int... values) {...} void printValues(int a, int b) {...}
Passing an array vs varargs in Java:
void processArray(int[] arr) {...} void processVarargs(int... values) {...}
Java varargs and type safety:
void displayStrings(String... strings) {...}