Wednesday 3 September 2014

15. varargs(variable arguments) in java

In java, arguments are passed in methods and constructors.
In a method/constructor, if number of arguments are changing but datatype is same, in that case instead of overriding the method, we can use varargs(variable arguments).

Below is how we can define method which takes argument of type vararg:
public void method1(int ...args){
...
}

Identifier of the varagr acts as an array of the specific type. In above method, args will act as an array of int.
However, we can have only one varagr in any method or constructor and it must be the last argument.

Suppose we want to print different technologies dynamically.

public class VarArgsDemo{
 
 public static void main(String args[]){
  varArgsTest();
  varArgsTest("java");
  varArgsTest("java", "sql");
  varArgsTest("java", "C++", "sql");
 }
 
 public static void varArgsTest(String ...args){
  for(String i:args){
   System.out.println(i);
  }
  System.out.println("----");
 }
}

OUTPUT:

----
java
----
java
sql
----
java
C++
sql
----






No comments:

Post a Comment