[Java] Variable Arguments in java?!

less than 1 minute read

From these posts, you’ve learned that python supports getting unfixed number of multiple parameters in functions.
Dealing with multiple parameters in python - *args (1) Dealing with multiple parameters in python - **kwargs (2)

Surprisingly, I recently found out that Java (from JDK 5) also supports the same feature!

class VarArgs
{ 
    // A method that takes variable number of integer 
    // arguments. 
    static void test(int... num) 
    { 
        System.out.println("Number of arguments: " + num.length); 
   
        for (int elem : num){
            System.out.print(elem + " " + "\n"); 
        } 
    } 
  
    public static void main(String args[]) { 
        
        test(1);         
        test(1, 2, 3, 4);  
        test();             
    } 
} 

You can find variable arguments example from java ProcessBuilder.

public ProcessBuilder(String... command) 

https://www.geeksforgeeks.org/variable-arguments-varargs-in-java/ https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

Leave a comment