Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Using Varargs (variable arguments)

Java Examples - Using Varargs

Java Examples Java Examples

Java 1.5 provides a new feature called varargs, which means variable-length arguments.

"Varargs" means "variable number of arguments". Sometimes it is also simply called "variable arguments"

To define a method with a variable number of actual arguments: just add three consecutive "." (i.e. "...", the ellipsis in English) between the "type" and the "parameter name" of a formal parameter, and it will match an indeterminate number of actual arguments.

The following example creates the sumvarargs() method to total the values of all numbers:

Main.java File

public

class

Main

{

static

int

sumvarargs

(

int

...

intArrays

)

{

int

sum

,

i

;

sum

=

0

;

for

(

i

=

0

;

i

<

intArrays

.

length

;

i

++

)

{

sum

+=

intArrays

[

i

]

;

}

return

(

sum

)

;

}

public

static

void

main

(

String

args

[

]

)

{

int

sum

=

0

;

sum

=

sumvarargs

(

new

int

[

]

{

10

,

12

,

33

}

)

;

System

.

out

.

println

(

"

The sum of the numbers is:

"

sum

)

;

}

}

The output of the above code is:


数字相加之和为: 55

Java Examples Java Examples