Home > Java > javaTutorial > How Do Variable Arguments (Varargs) Work in Java?

How Do Variable Arguments (Varargs) Work in Java?

Patricia Arquette
Release: 2024-12-19 17:49:09
Original
567 people have browsed it

How Do Variable Arguments (Varargs) Work in Java?

Variable Arguments in Java

In Java, the three dots (also known as varargs) following the parameter type, such as in the method below, signify variable arguments:

public void myMethod(String... strings) {
    // method body
}
Copy after login

Meaning

This means that you can pass zero or more String objects (or a single array of them) as arguments to the method. For instance, you can call the method as follows:

myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});
Copy after login

Behavior

It's important to note that the arguments passed using varargs are always stored in an array. Even if there's only one argument, it's converted into an array. This behavior must be accommodated in the method body.

Limitations

The parameter that uses varargs must be the last parameter in the method signature. For example, the following method signature is valid:

myMethod(int i, String... strings)
Copy after login

However, the following method signature is invalid:

myMethod(String... strings, int i)
Copy after login

The above is the detailed content of How Do Variable Arguments (Varargs) Work in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template