"Java Basics" mutable parameters

Source: Internet
Author: User

The following is a simple applet:

1 import java.util.Arrays;2 3 classLesson64 {5      Public Static voidMain (string[] args)6     {7         intarray[]={2,3,1,5,4,6};8System. out. println (arrays.tostring (array));9System. out. println (getsum (array));Ten         //System.out.println (Getsum (2,3,1,5,4,6)); One     } A  -     Static intGetsum (intArray[])//Sum of the calculated elements -     { the         intsum=0; -          for(intI=0; i<array.length;i++) -sum+=Array[i]; -         returnsum; +     } -}
View Code

Where the declaration of the getsum (int array[]) method qualifies it to accept only one-dimensional array of type int. If we now try to run line tenth (the line that is commented on), it will definitely go wrong. This method is declared in particular when it is not known to pass in the number of parameters, the shortcomings are obvious.

Starting with JAVA5, variable parameters are present. Features: variable number of parameters, you can pass 0 to N, must be the last parameter of the method, when the method of the variable parameter is called, the compiler implicitly creates an array for the variable parameter, and accesses the variable parameter in the form of an array in the method body.

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

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

In addition, one thing that needs special attention in practical programming is that the variable parameter must be the last parameter of the method. You can experiment with simple changes to the above code.

"Java Basics" mutable parameters

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.