Home > Java > javaTutorial > How to use variable length parameters in java

How to use variable length parameters in java

angryTom
Release: 2020-02-03 13:56:50
Original
3649 people have browsed it

How to use variable length parameters in java

How to use variable-length parameters in java

The syntax of the variable-length parameter method is as follows:

返回值 方法名(参数类型...参数名称)
Copy after login

Use the "..." form in the parameter list to define variable-length parameters. In fact, the variable-length parameter a is an array. The compiler will regard the form (int...a) as (int[] a) form.

Example: Write a variable-length parameter method.

/**
 * 定义不定长参数方法
 * 
 * @author pan_junbiao
 *
 */
public class MyTest
{
    public static int add(int... a)
    {
        int s = 0;
        for (int i = 0; i < a.length; i++)
        {
            s += a[i];
        }
        return s;
    }
 
    public static void main(String[] args)
    {
        // 调用不定长参数方法
        System.out.println("调用不定长参数方法:" + add(1, 2, 3, 4, 5, 6, 7, 8, 9));
        System.out.println("调用不定长参数方法:" + add(1, 2));
    }
}
Copy after login

Running results:

调用不定长参数方法:45
调用不定长参数方法:3
Copy after login

(Related video tutorial sharing: java video tutorial)

The above is the detailed content of How to use variable length parameters in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template