Java varargs allows methods to accept a variable number of arguments.
In this chapter, you will learn about Java varargs, how it works, and how it simplifies method calls by allowing multiple arguments.
Varargs (variable arguments) allow a method to accept zero or more arguments of the same type.
Before varargs, developers used method overloading or arrays to handle multiple parameters. If the number of arguments is unknown, varargs is a better and more flexible approach.
The varargs feature uses ellipsis (...) after the data type to allow a method to accept multiple arguments.
To create a method with varargs, we use three dots (...) after the data type. The syntax is as follows:
While using varargs, you must follow certain rules; otherwise, the program will not compile. The rules are as follows:
In the following examples, the code fails to compile because it violates the rules of varargs usage:
In this example, the varargs parameter is correctly placed at the end of the method.
Output:
number is 500 hello number is 1000 my name is varargs
We request you to subscribe our newsletter for upcoming updates.