14-variable length arguments in java

  • By using var args we can write java codes to accept zero to many values.

public class Testing {

    void m(int ...x){
        System.out.println(x);
        for (int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }
    }

    public static void main(String args[]){
        Testing t = new Testing();

        t.m(2,6,-6);// we can give zero to many integer values here
        t.m(2,6,-6,4,6,8,9);
    }
}
  • Now lets see how to combine var args with other parameters.

public class Testing {
/*var arg parameter should come last in the parameter list*/
    void m(int ...x,int y){ // In here all the values will catch by var args

    }

    public static void main(String args[]){
        Testing t = new Testing();

        t.m(2,6,-6);//in here its give a compile error

    }
}
  • Note : Only one var arg parameter can exist in a parameter list.

Leave a comment