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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-20 12:41:11633browse

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
}

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
  • Multiple Arguments:

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

    myMethod("solo");
  • Array Argument:

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

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!

Statement:
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