You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Java Tutorial: Variable Arguments (VarArgs) in Java
2
+
- In the previous tutorial, we discussed how we can [overload the methods in Java.](https://github.com/kishanrajput23/Java-Tutorials/blob/main/32.Method_Overloading/README.md)
3
+
- Now, let's suppose you want to overload an "add" method. The "add" method will accept one argument for the first time and every time the number of arguments passed will be incremented by 1 till the number of arguments is equaled to 10.
4
+
- One approach to solve this problem is to overload the "add" method 10 times. But is it the optimal approach? What if I say that the number of arguments passed will be incremented by 1 till the number of arguments is equaled to 1000. Do you think that it is good practice to overload a method 1000 times?
5
+
- To solve this problem of method overloading, Variable Arguments(Varargs) were introduced with the release of JDK 5.
6
+
- With the help of Varargs, we do not need to overload the methods.
7
+
- Syntax :
8
+
9
+
```
10
+
/*
11
+
public static void foo(int … arr)
12
+
{
13
+
// arr is available here as int[] arr
14
+
}
15
+
*/
16
+
```
17
+
18
+
- foo can be called with zero or more arguments like this:
19
+
1. foo(7)
20
+
2. foo(7,8,9)
21
+
3. foo(1,2,7,8,9)
22
+
23
+
24
+
- Example of Varargs In Java :
25
+
26
+
```
27
+
class calculate {
28
+
29
+
static int add(int ...arr){
30
+
int result = 0;
31
+
for (int a : arr){
32
+
result = result + a;
33
+
}
34
+
return result;
35
+
}
36
+
37
+
public static void main(String[] args){
38
+
System.out.println(add(1,2));
39
+
System.out.println(add(2,3,4));
40
+
System.out.println(add(4,5,6));
41
+
}
42
+
}
43
+
```
44
+
45
+
```
46
+
Output :
47
+
3
48
+
9
49
+
15
50
+
```
51
+
52
+
**Handwritten Notes: [Click to Download](https://api.codewithharry.com/media/videoSeriesFiles/courseFiles/java-tutorials-for-beginners-33/Ch7.pdf)**
53
+
54
+
**Ultimate Java Cheatsheet: [Click To Download](https://api.codewithharry.com/media/videoSeriesFiles/courseFiles/java-tutorials-for-beginners-33/UltimateJavaCheatSheet.pdf)**
0 commit comments