Demonstrate use of 'varagrs' in Java

The varargs is variable length arguments that allows the method to accept zero or multiple arguments. Before varargs either we use overloaded method or take an array as the method parameter. If we don't know how many argument we will have to pass in the method, varargs is the better approach. The main advantage of is that we don't have to provide overloaded methods as a result so less code. The syntax for varargs is given below:
return_type    method_name( data_type...    variable-name){
 .
 .
}  

Note that you have to insert three dots(...) after data type.

In program we have create a method sum( ) which gets variable length arguments. Then we call sum( ) method in main( ) method by providing different number of arguments.


PROGRAM
class VarArgsDemo {

 public static void sum(int... a) {
  
  int sum=0;
  for(int i=0;i<a.length;i++) {
   
   sum+=a[i];
  }
  System.out.println("The sum is "+sum);
 }

 public static void main(String[] args) {
 
  sum(1,2,4,5);
  sum(1,2);
  sum();
 }
}
OUTPUT
C:\>javac VarArgsConstDemo.java
C:\>java VarArgsConstDemo
The sum is 10
The sum is 30
The sum is 60

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.