How to use three dots (...) to allow zero to multiple arguments to be passed to a function in Java

1 Answer

0 votes
public class MyClass {
    public static int function (int ... num) {
        int sum = 0;
        
        for (int n : num)
            sum += n;
        
        return sum;
    }
    
    public static void main(String args[]) {
        System.out.println(function(1, 2));
        System.out.println(function(1, 2, 3));
        System.out.println(function(1, 2, 3, 4));
    }
}




/*
run:

3
6
10

*/

 



answered Jun 8, 2023 by avibootz
...