Variable Arguments

Vinnu Mukhi
1 min readMay 28, 2021

A simple program of VarArgs!

package com.company;

public class varages {
static int sum(int a,int b){
return a+b;
}
public static void main(String[] args) {
System.out.println("The sum of 4 and 5 is: "+ sum(4,5));
}
}
Output: The sum of 4 and 5 is: 9

Taking 2 methods!

package com.company;

public class varages {
static int sum(int a,int b){
return a+b;
}
static int sum(int a,int b, int c){
return a+b+c;
}
public static void main(String[] args) {
System.out.println("The sum of 4 and 5 is: "+ sum(4,5));
System.out.println("The sum of 4, 5 and 6 is: "+ sum(4,5, 6));
}
}
Output: The sum of 4 and 5 is: 9
The sum of 4, 5 and 6 is: 15

Using varArgs to access the method

static int sum(int...arr){
int result=0;
for (int a: arr){
result +=a;
}
return result;
//by this way we can create ultimate results
}
public static void main(String[] args) {
System.out.println("The sum of 4 and 5 is: "+ sum(4,5));
System.out.println("The sum of 4, 5 and 6 is: "+ sum(4,5, 6));
System.out.println("The sum of 4,5,6 and 9 is: "+ sum(4,5,6,9));
}
}
Output: The sum of 4 and 5 is: 9
The sum of 4, 5 and 6 is: 15
The sum of 4,5,6 and 9 is: 24

--

--

Vinnu Mukhi
0 Followers

I'm a Computer Science Student from Indore (India) and I'm Sharing all my learnings here.