Variable parameter comparisons in C # and Java

Source: Internet
Author: User

Variable parameters in C # with the keyword params

Codepublic class App {        static void Main () {            //general use Method            Console.WriteLine (ADD (New int32[] {1, 2, 3, 4, 5})) ;            Another method of calling            Console.WriteLine (ADD (1, 2, 3, 4, 5));            Of course, the number of parameters is variable, but its type is constrained by the            Console.WriteLine (ADD (1, 2, 3, 4, 5, 6, 7, 8, 9, ten, one, one, one, and many));            What if the type is variable and the number is variable? The answer to the book is very simple, which is to use the object type            //Note down}//<summary>//        Use the params keyword        </summary>        //<param Name= "values" >int[]</param>        //<returns>int[] and </ returns>        static Int32 Add (params int32[] values) {            Int32 sum = 0;            for (int x = 0; x < values. Length; x + +)                sum + = values[x];            return sum;

Three dots in Java ...

1), can only appear at the end of the parameter list;

2) 、... Between the variable type and the variable name, there are no spaces before and after it can be;

3), when invoking a variable parameter method, the compiler implicitly creates an array for the variable parameter, accessing the mutable parameter in the form of an array in the method body.

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;
}
}

Variable parameter comparisons in C # and Java

Related Article

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.