Java variable parameter usage example _java

Source: Internet
Author: User

Java1.5 adds new features: Variable parameters: The case where the parameter number is indeterminate and the type is determined, Java treats the variable parameters as an array. Note: The variable parameter must be in the last item. When the number of variable arguments is more than one, there is bound to be one that is not the last, so only one variable parameter is supported. Because of the indefinite number of parameters, Java cannot distinguish between the previous variable or the next parameter when the same type parameter is behind it, so you can only have the variable argument in the last item.

Characteristics of variable parameters:

1, can only appear at the end of the list of parameters;

2 、... Is between the variable type and the variable name, and before and after the space can be;

3. When you invoke 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.

Copy Code code as follows:

public class Varable {
public static void Main (String [] args) {
System.out.println (Add (2,3));
System.out.println (Add (2,3,5));
}
public static int Add (int x,int ... args) {
int sum=x;
for (int i=0;i<args.length;i++) {
Sum+=args[i];
}
return sum;
}
}


Example code 2

Copy Code code as follows:

public static void Main (string[] args) {
T.test ("1", "2", "3");
}
public static void Test (String ... PS) {
System.out.println (ps.length);
for (String S:ps) {
System.out.println (s);
}
}

The top PS corresponds to a string array

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.