What is Varargs? How to overload varargs methods?

What is Varargs? How to overload varargs methods?

What is Varargs? How to overload varargs methods? Explain with demo example.

What is Varargs?

Varargs (Variable Arguments) in Java allows a method to accept a variable number of arguments. It makes it easier to write methods where you don’t know in advance how many arguments might be passed. Instead of explicitly defining multiple parameters for each possible argument, you can define a single parameter followed by an ellipsis (...), which allows you to pass any number of arguments (including none).

Syntax:

public void methodName(dataType... parameterName) {
    // method body
}
  • dataType can be any valid Java data type (like int, String, etc.).
  • The parameterName is a variable name that will be treated as an array.

Example of Varargs:

Here’s a simple example that demonstrates a method using varargs:

public class VarargsExample {
    // Method that accepts any number of integers
    public static void printNumbers(int... numbers) {
        for (int number : numbers) {
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        // Call the method with different numbers of arguments
        printNumbers(1, 2, 3);
        printNumbers(10, 20, 30, 40);
        printNumbers(); // No arguments
    }
}

Output:

1
2
3
10
20
30
40