Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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
Author

method with an unknown number of parameters

Joseph Sweet
Ranch Hand

Joined: Jan 29, 2005
Posts: 327
Hi,
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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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)
sum(3, 4, 5)
sum(3, 4, 5, 6, 7)

etc.


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

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

Tzk

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.

J.
 
jQuery in Action, 2nd edition
 
subject: method with an unknown number of parameters