-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVarArgs.java
More file actions
65 lines (47 loc) · 1.72 KB
/
VarArgs.java
File metadata and controls
65 lines (47 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class VarArgs {
// Varargs (Variable Arguments) allows you to pass a variable number of arguments to a method.
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Normally, you would have to define multiple methods to handle different numbers of arguments, but with varargs, you can handle them all with a single method.
public static int sum(int a, int b) {
return a + b;
}
public static int sumArray (int [] numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Varargs with minimum one argument
public static int sum(int first, int... numbers) {
int total = first; // Start with the first argument
for (int num : numbers) {
total += num;
}
return total;
}
// Varargs with two arguments
public static int sum(int first, int second, int... numbers) {
int total = first + second; // Start with the first two arguments
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
// Using the sum method with Normal parameters
System.out.println(sum(5, 10)); // Output: 15
// Using the sum method with an array
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(sumArray(numbers)); // Output: 15
// Using the sum method with Varargs
System.out.println(sum(numbers)); // Output: 15
System.out.println(sum()); // Output: 0
}
}