In this tutorial we will see about Variable Arity method in Java. Variable Arity method question is bit old interview question which used widely before JDK 5. But good to know about this feature in Java and also in Java 7 we have got an update with @SafeVarargs.
Its nothing but passing an arbitrary set of arguments to a method. Method can have N no. of arguments but the condition that we can't pass arguments after Arity member. Arity member variable should be always last in the method and it can be primitive or non-primitive data type. Below are the few valid and invalid Variable Arity method definition in Java.
Its nothing but passing an arbitrary set of arguments to a method. Method can have N no. of arguments but the condition that we can't pass arguments after Arity member. Arity member variable should be always last in the method and it can be primitive or non-primitive data type. Below are the few valid and invalid Variable Arity method definition in Java.
Valid:
public void myMethod(int... arg){....}
public void myMethod(String... arg){....}
public void myMethod(Object... arg){....}
public void myMethod(int a, int b, int... arg){....}
Invalid:
public void myMethod(int... arg, int a){....}
Lets see small sample code how to pass values to Variable Arity method and how to print those values.
public class ArityMethod {
public static void myMethod1(int... arg){
System.out.print("\nmyMethod1 : ");
for (int i : arg) {
System.out.print(i+", ");
}
}
public static void myMethod2(String... arg){
System.out.print("\nmyMethod2 : ");
for (String str : arg) {
System.out.print(str +" ");
}
}
public static void myMethod3(int a, float b, Object... arg){
System.out.print("\nmyMethod3 a value : "+a);
System.out.print("\nmyMethod3 b value : "+b);
System.out.print("\nmyMethod3 : ");
for (Object str : arg) {
System.out.print(str.toString() +" ");
}
}
public static void main(String[] args) {
myMethod1(1,2,3,4,5);
myMethod2("hello", "welcome", "to", "Java Discover");
myMethod3(100,3.0f, "hello", "welcome", "to", "Java Discover");
}
}
OUTPUT:
myMethod1 : 1, 2, 3, 4, 5,
myMethod2 : hello welcome to Java Discover
myMethod3 a value : 100
myMethod3 b value : 3.0
myMethod3 : hello welcome to Java Discover
No comments:
Write comments