Saturday, February 7, 2009

Var-arg method(Variable argument method)

Variable argument method: variable argument methods (var-arg methods)allow us to specify that a method can take multiple arguments of the same type and allows the number of arguments to be variable.

See problem :
class Sample {
public void m1(int x) {
System.out.println(“int var”);
}
public static void main(String arg[]) {
Sample s=new Sample();
s.m1(10);
s.m1(); ---------------> error
s.m1(10,20); -----------> error
}
}


var -arg Syntax :
public void m1(int… a) {
System.out.println(“var-arg method”);
}
a var- arg method can be declared as follows
public void m1(type… name)

Variable argument method Example:
class Sampe {
void m1(int… a) {
System.out.println(“var- arg”);
}
public static void main(String arg[]) {
Sample s=new Sample();
s.m1();
s.m1(10);
s.m1(10,20);
}
}
}

In the var- arg method ,we can take normal parameters also in addition to var-arg parameter .But var-arg parameter must be the last parameter in the method deceleration.violation leads to compile time error.

Case1:
m1(char ch,int… a) { ---- } ------> valid

Case 2:
m1(int… a,char ch) {-----} -------> not valid
In the var- arg method only one no-arg parameter is allowed .i.e more than onr=e var-arg parameter is not allowed ,violation leads CTE.

m1(int… a, char… ch) {----} -------> not valid.
Only one var-arg parameter is allowed and that must be last parameter.

Case3:The var-arg method will get the last priority. i.e. if no other normal method is matched at the time only we should go for var-arg method.

Ex.
class Sample
{
public void m1(int… a)
{
System.out.println(“var-arg method”);
}
public void m1(int a)
{
System.out.println(“normal method”);
}

public static void main(String arg [])
{
Sample s=new Sample();
s.m1(10); //
Normal method
}
}
Case 4:
we can write main method like this also public static void main(String... arg)

Related Posts..........

var-arg Vs normal method example while overloading
.


main method And Commandline arguments

0 comments:

Post a Comment