File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes method with an unknown number of parameters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "method with an unknown number of parameters" Watch "method with an unknown number of parameters" New topic

method with an unknown number of parameters

Joseph Sweet
Ranch Hand

Joined: Jan 29, 2005
Posts: 327
I need to write a method that can get an unknown number of int parameters...
do you know what should be the syntax for that. I know the syntax in C++, do not have a clue what it is in java.

the method should do something really simple, like summing up the numbers it gets. problem is one time I can call it with 5 numbers and the next time with 10 etc.
[ May 07, 2005: Message edited by: Joseph Sweet ]

We must know, we will know. -- David Hilbert
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

This feature (commonly called "varargs") was introduced in Java 5; it didn't exist previously. Even so, it's actually just synactic sugar for a final argument of array type.

A function sum() that added an arbitrary number of int arguments would look like

And you could then call

sum(3, 4, 5)
sum(3, 4, 5, 6, 7)


[Jess in Action][AskingGoodQuestions]
Jeffrey Spaulding
Ranch Hand

Joined: Jan 15, 2004
Posts: 149
Hmmm varargs, we have that now?


Anyway, if you don't use 5 you might do it a little different.

You could pass an Array of ints to a sum function.

I agree. Here's the link:
subject: method with an unknown number of parameters
It's not a secret anymore!