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

How to use variable length parameters in java

angryTom
angryTomOriginal
2020-02-03 13:56:503623browse

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:

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

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));
    }
}

Running results:

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

(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!

Statement:
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