Variable parameters in Java

Source: Internet
Author: User

Variable parameters in Java

Java adds a new feature: variable parameters: this feature is applicable to situations where the number of parameters is uncertain and the type is determined. java treats variable parameters as arrays.

Features:
1. It can only appear at the end of the parameter list;
2. The ellipsis (...) is located between the variable type and the variable name. It can be preceded by spaces.
3. When the variable parameter method is called, the compiler implicitly creates an array for the variable parameter,
Access variable parameters in the form of arrays in the method body

Program example:

Public class Test {// evaluate the public void add (int x, int... arr) // variable parameter {int sum = x; // first copy the value of the first parameter to sumfor (int I = 0; I <arr. length; ++ I) {sum + = arr [I];} System. out. println (sum);} public static void main (String [] args) {// TODO Auto-generated method stubTest tt = new Test (); tt. add (2); // The sum is 2. The variable parameter length can be 0 tt. add (2, 3); // and 5tt. add (2, 3, 4, 5); // The sum is 14tt. add (2, 3, 4, 5, 6, 7 );}}



Usage of variable-length parameters in java

Easy to write code ..

For example, public void method (int... a) {} is an int array in this method body ..

But if it is written as public void method (int [] .. When using this method .. You must upload the array ..

You can change the parameter to method (1, 2, 3. You do not need to use mehotd (new int [] {1, 2, 3 }).. You can also upload an array .. Convenient

How does one define variable parameters in java?

Method overload,
Syntax:
Access modifier (public) method type (void, etc.) method name (parameter 1, parameter 21 ·) {method subject}
The method type and method name are consistent. The corresponding method is automatically selected based on different parameter types and numbers.

Please adopt it!

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.