When do you use varargs in Java?

后端 未结 8 1760
猫巷女王i
猫巷女王i 2020-11-22 04:47

I\'m afraid of varargs. I don\'t know what to use them for.

Plus, it feels dangerous to let people pass as many arguments as they want.

What\'s an example

8条回答
  •  盖世英雄少女心
    2020-11-22 05:28

    Varargs is the feature added in java version 1.5.

    Why to use this?

    1. What if, you don't know the number of arguments to pass for a method?
    2. What if, you want to pass unlimited number of arguments to a method?

    How this works?

    It creates an array with the given arguments & passes the array to the method.

    Example :

    public class Solution {
    
    
    
        public static void main(String[] args) {
            add(5,7);
            add(5,7,9);
        }
    
        public static void add(int... s){
            System.out.println(s.length);
            int sum=0;
            for(int num:s)
                sum=sum+num;
            System.out.println("sum is "+sum );
        }
    
    }
    

    Output :

    2

    sum is 12

    3

    sum is 21

提交回复
热议问题