Sunday, 29 January 2017

VARARGS IN JAVA

It works like method overloading, but it’s not method overloading. Varargs is a new approach in java. Before the concept of varargs we were using method overloading. But what suppose if we don’t know the number of arguments to pass into the method then at that situation we use varargs. Syntax – datatype…variablename.

Example –
public class Vararg1 {       
          public void sum(int...sum)
          {
                   int result = 0;
                   for(int s : sum)
                   {
                             result = result+s;
                   }
                   System.out.println("The sum is : "+result);
          }
          public static void main(String[] args) {
                   Vararg1 v = new Vararg1();
                   v.sum(10,20,30);
                   v.sum(50,10);
                   v.sum(1,2,3,5,7,8,9);
          }
}

Output –
The sum is : 60
The sum is : 60
The sum is : 35

Example –
public class Vararg1 {       
          public void display(String...name)
          {
                   for(String names : name)
                   {
                             System.out.print(names+" ");
                   }
                   System.out.println();           
          }
          public static void main(String[] args) {
                   Vararg1 v = new Vararg1();
                   v.display("rakesh","mukesh","pramod");
                   v.display("Haary","Smith");
                   v.display("Smith","Miller","Adam","Sahil");             
          }
}

Output –
rakesh mukesh pramod
Haary Smith
Smith Miller Adam Sahil

Rules for varargs – While using the varargs, we must follow some rules otherwise program code won’t compile. The rules are as follows –
  • ·        There can be only one variable argument in the method.
  • ·        Variable argument (varargs) must be the last argument.


Example –
void method(String… a, int… b) { }                   //Compile time error
void method(int… a, String b) { }                     //Compile time error

Example –
public class Vararg2 {
          public void display(String name,int... marks)
          {
                   int total = 0;
                   System.out.print(name+" ");
                   for(int res : marks)
                   {
                             total = total+res;                   
                   }
                   System.out.print("your total marks is = "+total);
                   System.out.println();
          }
          public static void main(String[] args) {
                   Vararg2 v = new Vararg2();
                   v.display("rakesh", 95,88,73,96);
                   v.display("Harry", 88,87,98,83);
          }
}

Output –
rakesh your total marks is = 352

Harry your total marks is = 356

No comments:

Post a Comment