Learn Java's variable parameters from zero _java

Source: Internet
Author: User

Here's a simple little program:

Copy Code code as follows:

Import Java.util.Arrays;

Class Lesson6
{
public static void Main (string[] args)
{
int array[]={2,3,1,5,4,6};
System.out.println (arrays.tostring (array));
System.out.println (Getsum (array));
System.out.println (Getsum (2,3,1,5,4,6));
}

static int getsum (int array[])//sum of calculated elements
{
int sum=0;
for (int i=0;i<array.length;i++)
Sum+=array[i];
return sum;
}
}

The declaration of the getsum (int array[]) method qualifies it to accept only arrays of one-dimension int. If we are now trying to run line tenth (the line that is commented on), this will definitely go wrong. This method of declaring the way especially when you do not know to pass the number of parameters, the disadvantage is more obvious.

Starting with JAVA5, a variable parameter appears. Features are: variable number of parameters, you can pass 0 to n; You must be the last parameter of a method; When you call a method of a variable parameter, the compiler implicitly creates an array for the variable parameter, which accesses the variable parameter in the form of an array in the method body.

We cancel the comment on the code above and change getsum (int array[]) to getsum (int ... array) to achieve the results we want. The results obtained are as follows:

From the bottom two output 21 is available, getsum (int ... array) successfully received 2 different numbers of data passed in.

In addition, in practical programming, it is necessary to note that the variable parameter must be the last parameter of the method. You can make a simple change to the code above to experiment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.