Commit b806766
committed
feat: Add SumElementsVarargs to calculate sum of integers using varargs
WHAT the code does:
Defines a SumElementsVarargs class with a sum(int... A) method:
- Accepts a variable number of integer arguments (varargs).
- Iterates through them, accumulating a total sum.
- Returns the computed result.
main() demonstrates usage by summing 1, 2, 3, 4, 5 → result = 15.
WHY this matters:
Showcases Java varargs, which simplify APIs by allowing flexible numbers of arguments without overloading.
Demonstrates iteration over varargs using a traditional for loop.
Encapsulates reusable logic in a method that adapts to different input sizes.
Provides a concise alternative to array-based summation.
HOW it works:
When obj.sum(1, 2, 3, 4, 5) is called:
- Java internally creates an int[] array {1, 2, 3, 4, 5}.
- The method iterates from index 0 to A.length-1, adding elements to total.
- Returns 15, which is printed in main().
Tips and gotchas:
Varargs are syntactic sugar for arrays; at runtime, an array is always created.
Be cautious when mixing varargs with other parameters—varargs must come last in the method signature.
If no arguments are passed, A.length == 0 and total will remain 0.
For performance-sensitive cases with frequent calls, repeated array creation may be costly.
Use-cases:
Utility function for summing numbers without requiring manual array creation.
Educational demonstration of varargs in Java.
Foundation for building statistical helpers (average, min, max) using varargs.
Simplifies method calls in APIs that handle flexible input sizes.
Short key: class-sumelementsvarargs varargs integer-sum.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent a2a4de5 commit b806766
1 file changed
+6
-12
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | | - | |
| 3 | + | |
| 4 | + | |
5 | 5 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
| 6 | + | |
10 | 7 | | |
11 | 8 | | |
12 | 9 | | |
13 | 10 | | |
14 | | - | |
15 | | - | |
16 | | - | |
| 11 | + | |
17 | 12 | | |
18 | 13 | | |
19 | | - | |
20 | 14 | | |
21 | 15 | | |
22 | 16 | | |
23 | | - | |
| 17 | + | |
0 commit comments