Posts Tagged variable argument

Demonstrates the VARARGS feature of java for variable arguments along with normal parameters.

Here we demonstrate how we can pass normal parameter along with varible arguments.

class VarExample

{ public void Test(String str, int ... arr)

{System.out.print(str + arr.length + "contents ");

for(int i : arr){

System.out.print(i+" ");}

System.out.println();

}

public static void main(String a[])

{VarExample ve =new VarExample();

ve.Test("First argument",1);

ve.Test("Second argument", 11, 12,13);

ve.Test(" No variable arguments ");

}
}

, , , ,

2 Comments

Demonstrates the VARARGS feature of java for variable arguments.

This example shows how to use VARAGRS feature of java for variable length arguments instead of using array.

class VarExample

{

public void test(int ... arr)

{

System.out.print("No. of arguments "+arr.length+"contents ");

for(int i: arr)

{ System.out.print( i+ " ");

}

System.out.println();

}

public static void main(String a[])

{ VarExample ve= new varExample() ;

va.Test(10);

va.Test(11,12,13,14);

va.Test();

}
}

, ,

No Comments

Variable length argument implemented using array.

This Example demonstrates how we can pass variable argument using array, but this approach is old. Now a days we use Varargs feature included in J2SE 5.

class VariableArr{
public void Test(int[] arr)

{ System.out.println("No. of args "+arr.length+"contents ");

for(int i : arr)

{ System.out.print( i+" ");

}

System.out.println();

}

public static void main(String a[])

{ VariableArr va= nw VariableArr();

int a[]= {20};

int b[]={2,4,6};

int c[]= {};

va.test(a);

va.test(b);

va.test(c);

}

}

, ,

2 Comments