Home >Java >Javagetting Started >What are variable length parameters in java?

What are variable length parameters in java?

青灯夜游
青灯夜游Original
2019-12-31 16:49:523559browse

What are variable length parameters in java?

Indefinite length parameters in java

Indefinite length parameters are parameters with no specified length.

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

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

Use the "..." form in the parameter list to define the variable-length parameter. In fact, this variable-length parameter is a For arrays, the compiler will treat the form (int...a) as the form (int[] a).

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:

What are variable length parameters in java?

Recommended learning: Java video tutorial

The above is the detailed content of What are 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