Commit 5d0d7f4
committed
feat: Add VarArgs class demonstrating Java variable arguments (varargs)
WHAT the code does:
- Defines a `VarArgs` class showcasing different uses of varargs (`...`).
- `fun(int... v)`: accepts variable number of integers and prints them as an array.
- `demo(int... v)`: overloaded method handling integer varargs.
- `demo(String... v)`: overloaded method handling string varargs.
- `multiple(int a, int b, String... v)`: combines fixed parameters with varargs.
- `main()` demonstrates calling each method with different argument sets.
WHY this matters:
- Demonstrates how **varargs** allow flexible method calls without manually creating arrays.
- Shows **method overloading** with different vararg types.
- Useful for simplifying APIs where the number of parameters is not fixed.
- Highlights that varargs are internally treated as arrays.
HOW it works:
1. `fun(1, 2, 3, 4)` → prints `[1, 2, 3, 4]`.
2. `multiple(2, 3, "Kunal", "Rahul", "dvytsbhusc")` → prints integers and string list.
3. `demo(5, 6, 7)` → resolves to `demo(int... v)` → prints `[5, 6, 7]`.
4. `demo("A", "B", "C")` → resolves to `demo(String... v)` → prints `[A, B, C]`.
Tips & gotchas:
- Only one varargs parameter allowed per method, and it must be the last parameter.
- Varargs can be called with zero arguments (e.g., `fun()` → prints empty array).
- Ambiguity may arise if overloaded methods have similar vararg signatures.
- Varargs incur slight performance overhead since arguments are wrapped in an array.
Use-cases:
- Flexible APIs (e.g., logging methods like `log(String... messages)`).
- Utility methods where number of inputs may vary.
- Cleaner code for operations on collections of arguments.
- Educational example for **method overloading and varargs**.
Short key: class-varargs-overloading-demo.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 3e5bd29 commit 5d0d7f4
1 file changed
+16
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
6 | | - | |
7 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
8 | 12 | | |
9 | 13 | | |
| 14 | + | |
10 | 15 | | |
11 | | - | |
| 16 | + | |
12 | 17 | | |
13 | 18 | | |
| 19 | + | |
14 | 20 | | |
15 | | - | |
| 21 | + | |
16 | 22 | | |
17 | 23 | | |
| 24 | + | |
18 | 25 | | |
19 | | - | |
| 26 | + | |
| 27 | + | |
20 | 28 | | |
21 | 29 | | |
| 30 | + | |
22 | 31 | | |
23 | | - | |
| 32 | + | |
24 | 33 | | |
25 | 34 | | |
0 commit comments