Friday, 13 July 2012

Varargs in java (Passing variable no of arguments in java program)

After J2SE 5.0 java supports passing of variable arguments in a method that u don't need to fix the no of arguments at the time of defining the method .
Compiler automatically converts the arguments in the form of array so u can access all the arguments at run time.





Example:-


  1. public class Varargs
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6.  
  7. Varargs var = new Varargs();
  8.  
  9. var.show("Ankit", "Singh", "Katiyar");
  10.  
  11. var.show("facebook.com\"", "ankitkatiyar91");
  12.  
  13. }
  14.  
  15. public void show(String... arg)
  16.  
  17. {
  18.  
  19. for (int i = 0; i < arg.length; i++)
  20.  
  21. {
  22.  
  23. System.out.println(arg[i]);
  24.  
  25. }
  26.  
  27. }
  28.  
  29. }



Note:- it   works only it version J2SE 5.0 or above.

You can use any data type for variable arguments.

Example:-

package javaTest;

public class Varargs {

public static void main(String[] args) {
// TODO Auto-generated method stub
Varargs var=new Varargs();
var.show(1,2,3);
var.show(9,7);

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

}

Rules :-
* For any method it must be the last argument.

No comments:

Post a Comment