Home > Java > javaTutorial > What Do Three Dots (...) Mean in Java Method Parameters?

What Do Three Dots (...) Mean in Java Method Parameters?

Susan Sarandon
Release: 2024-12-20 12:41:11
Original
568 people have browsed it

What Do Three Dots (...) Mean in Java Method Parameters?

Understanding the 3 Dots in Java Parameter Types

When encountering a parameter type followed by three dots (...), it indicates a variable-length argument in Java. For instance, consider the following method:

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

The dots after String signify that you can pass zero or more String objects or a single array containing them as arguments to the myMethod method.

Examples of Method Invocation

You can call myMethod in various ways:

  • Empty Argument:

    myMethod(); // Possibly not useful but supported
    Copy after login
  • Multiple Arguments:

    myMethod("one", "two", "three");
    Copy after login
  • Single Argument:

    myMethod("solo");
    Copy after login
  • Array Argument:

    myMethod(new String[] {"a", "b", "c"});
    Copy after login

Important Considerations

  • The parameter with the three dots must be the last one in the method signature. For example, myMethod(int i, String... strings) is valid, but myMethod(String... strings, int i) is not.
  • The passed argument is always treated as an array, even if it contains just one element. Hence, you should handle it accordingly within the method body.

The above is the detailed content of What Do Three Dots (...) Mean in Java Method Parameters?. 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