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

What are variable length parameters in java?

青灯夜游
Release: 2019-12-31 16:49:52
Original
3548 people have browsed it

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:

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

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));
	}
}
Copy after login

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!

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