What does the term "String... string" mean in java?

Asked

Viewed 615 times

5

What the term means String... string in Java? And how to elaborate a method that returns a String... as an example:

public String... getStrings(){
     return String... s;)
}

I know it’s not like that, but I was wondering how you do it so I can pass as a parameter in a method like this:

public void setStrings(String... s){
      //codigo
}

Any suggestions?

1 answer

7


This is called varargs.

This is the way to indicate that the last parameter is actually a array of the type mentioned. Then the arguments in the method call can have a variable amount. That is, after the fixed and mandatory arguments, they can count from zero to "infinite" arguments provided that it is of the declared type.

When accessing s (in your example) remember that this variable is a array and must access it in this way.

Understand the difference between parameter and argument.

More details on What mean the reticence in the parameters of a method?

The return is not possible in this way, it only serves for parameters. Nor does it make sense to have something like this, after all this is a syntactic sugar. If you need to return multiple items you have to use one array or other normal data collection, such as a ArrayList or even a previously defined class.

public String[] getStrings() {
     return new String[] {"x", "y"};
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.