Commit 257d477
committed
feat: Add VariableArguments to demonstrate varargs and anonymous arrays
WHAT the code does:
Defines a VariableArguments class with:
- show(int... A): a varargs method that iterates through the provided integers and prints each one.
In main():
- Calls show() with no arguments, producing no output.
- Calls show(10, 20, 30) with multiple integers, printing them sequentially.
- Calls show(new int[]{3,4,5,6,7,8,9,10}) using an anonymous array.
WHY this matters:
Demonstrates Java varargs (variable-length arguments), which allow flexible method calls without explicit array creation.
Shows that varargs are syntactic sugar for arrays, making APIs cleaner and more user-friendly.
Introduces the concept of anonymous arrays—arrays created and passed directly without a named reference.
HOW it works:
show(int... A) compiles down to show(int[] A).
When invoked:
- show() → A is an empty array, loop body does not execute.
- show(10,20,30) → A is {10,20,30}, loop prints each element.
- show(new int[]{3,4,5,6,7,8,9,10}) → an anonymous array is passed, loop prints its contents.
Tips and gotchas:
Varargs must always be the last parameter in a method signature; only one varargs parameter is allowed per method.
If no arguments are provided, the varargs array is simply empty, avoiding null pointer issues.
Anonymous arrays are useful for quick one-off calls, but less readable for complex data.
For performance-sensitive cases, repeated varargs calls may incur overhead due to array creation.
Use-cases:
Educational demo of varargs and anonymous arrays in Java.
Utility methods that need flexibility (e.g., logging, math operations).
Foundation for designing clean, concise APIs where input size may vary.
Short key: class-variablearguments varargs anonymous-array.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9dc2c43 commit 257d477
1 file changed
+5
-9
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
8 | 5 | | |
9 | 6 | | |
10 | | - | |
11 | 7 | | |
12 | 8 | | |
13 | 9 | | |
14 | 10 | | |
15 | 11 | | |
16 | | - | |
| 12 | + | |
17 | 13 | | |
18 | 14 | | |
0 commit comments