Use of variable parameters in java

Source: Internet
Author: User

Many java api methods have the application of variable parameters. variable parameters, that is, the number of method parameters is not specified. You can enter a valid number of parameters at will. Variable parameters can be used to flexibly input parameters during method calling, similar to method overloading. Method overload: public void dosomething (int ){......} public void dosomething (int a, int B ){......} public void dosomething (int a, int B, int c ){......} if the method body processes the input parameters in the same way, such as summation and product calculation, you can consider the use of variable parameters: public void dosomething (int... nums ){......} example of variable parameters for summation: [java] public class ChangeParameterTest {public static void main (String [] args) {// call method of variable parameter methods 1 sum (1, 2, 3, 4, 5); // call method of variable parameter method 2 int arr [] = {1, 3, 5, 7}; sum (arr) ;}// sum publ with variable parameters Ic static void sum (int... nums) {// nums is an array int sum = 0; for (int I: nums) {sum + = I;} www.2cto.com System. out. println (sum) ;}}when using variable parameters: 1. variable parameters can only be placed at the end of the parameter list. Public void sum (int... nums, int y) unqualified public void sum (int y, int... nums) pass 2. In the method body, variable parameters can be accessed as arrays. Public void sum (int... nums) has int arr [] = nums;

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.