Friday, 10 May 2013

Top 3 Examples of variable arguments or varargs feature in java

Variable Arguments feature in java


Varargs Feature in java
Variable arguments feature is one of java language feature introduced in java 5. Java 5 introduced lot of new features like Enum feature[] etc.
method have multiple arguments, this arguments count are fixed, with Variable arguments feature in java5, method can have multiple arguments(zero to many) to be passed without defining number of arguments by specifying variable argument syntax. variable arguments are spcified in method defination by ellipse (...).

Before Varargs feature or prior to java 1.5:-
prior to java 1.5 version, developers has no chocie of variable arguments supplied but we

Java has a feature of method overloading in which same method can have different versions with changing arguments.


Advantages of Varargs feature:-


variable declarion not required at compile time or run time.
Clients have free control over passing variable arguments to Service API methods
backward compatability support for prior java versions


Variable argument syntax

We have to delcarate DataType ... arguments in method declaration


public void method(DataType ... arguments)

arguments are followed by ellipse ... meaning method accepts atleast zero arugments to mutiple arguments

Rules for Variable arguments


1. Varargs can be combined with other normal arguments.
2. Only one varargs in any method declaration
3. if there is combination of varargs and normal arguments, varargs declaration should be defined at last

JVM Execution for varargs:-


when variable argument is declared in method, java compiler of JVM loads that method and create a array of arguments of Data type

Varargs Simple example

package com.cloudhadoop.varargs;

public class VarargsExample {

static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
}
System.out.println(" " + sentence);
}

public static void main(String[] args) {
print("Hi", "How ", "are", "You");
}

}


and output is :- Hi How are you

Iteration of Varable arguments in java example


Variable arguments variable name is an reference to array of argument type. so we can use for each loop to iterate variable arguments


static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
}

0 comments:

Post a Comment