Today, we summarize the knowledge point of variable parameters in Java. Let's take a look at an example, and now I want to write a method to calculate the two shaping and output, which is simple:
publicclass KeBian { publicstaticvoidmain(String[] args) { sum(5,9); } publicstaticvoidsum(int a,int b) { int sum = a+b; System.out.println(sum); }}
The code is simple, there is no difficulty, now I want to add a number, ask three integers and output results, here I write another method:
publicstaticvoidsum(int a,int b,int c) { int sum = a+b+c; System.out.println(sum);}
If I want to add another parameter, is not to write another method, this method is very bad, because I want to write a lot of methods, code is very large, and very wasteful, what solutions? jdk5.0 provides the characteristics of variable parameters, that is, the number of parameters passed in the method can be changed. For the above example, we can change to the following code:
Public classKebian { Public Static void Main(string[] args) {SUM (5,9); Sum5,9,Ten); Sum5,9, One, -); } Public Static void sum(int... nums) {intsum =0; for(intI:nums) {sum+=i; } System. out. println (sum); }}
This will allow you to pass in any number of arguments without having to write multiple methods. The function of the nums here is actually analogous to an array, which saves the passed arguments to the array. Variable parameters can also be used in conjunction with individual parameters:
publicstaticvoidsum(int a,int...nums) { int0; for(int i:nums) { sum+=i; } System.out.println(a); System.out.println(sum); }
Note that at least one parameter is passed to a, and the following array can be used without passing the parameters, here to note, if you want to use with a single parameter, then the variable parameter part must be placed on the last side, because if the variable parameter is placed in front of the computer can not be judged to variable parameters passed a few values, and the program will error Another thing is that there can only be one variable parameter, so here's a little bit of attention.
Java Variable parameter summary