Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "params" in method signature?

In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.

I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.

like image 468
Omar Kooheji Avatar asked Feb 06 '09 10:02

Omar Kooheji


People also ask

What are considered for method signature in Java?

The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.

Is parameter order part of method signature?

For this, methods have signatures, where the order of parameters, exhibiting distinct patterns, gives the ability, to Java machine, to proceed with a correct and appropriate bindings and calls.

Can a method signature have a method body Java?

According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.

What does 3 dots mean in Java?

The "Three Dots" in java is called the Variable Arguments or varargs. It allows the method to accept zero or multiple arguments. Varargs are very helpful if you don't know how many arguments you will have to pass in the method.


1 Answers

In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:

public void foo(Object... bar) {     for (Object baz : bar) {         System.out.println(baz.toString());     } } 

The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[] in this case).

like image 105
3 revs Avatar answered Sep 23 '22 06:09

3 revs