Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: how can i create a function that supports any number of parameters?

is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ?

thanks

kfir

like image 990
ufk Avatar asked Nov 18 '10 14:11

ufk


People also ask

How do you write a function that accepts any number of arguments?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

How many parameters can a function have in Java?

There is a technical maximum of 255 parameters that a method can have.

Can a function have many parameters?

You can define as many parameters as you may need, but too many of them will make your routine difficult to understand and maintain.

How many parameters can a function accept?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.


1 Answers

Java has had varargs since Java 1.5 (released September 2004).

A simple example looks like this...

public void func(String ... strings) {     for (String s : strings)          System.out.println(s); } 

Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. For example, if you had a function that needed at least one string, and then a variable length argument list:

public void func2(String s1, String ... strings) {  } 
like image 110
逆さま Avatar answered Sep 30 '22 06:09

逆さま