Skip to content

Commit 257d477

Browse files
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

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed
Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
1-
public class VariableArguments
2-
{
3-
static void show(int ...A)
4-
{
5-
for (int x : A)
6-
{
7-
System.out.println(x);
1+
public class VariableArguments {
2+
static void show(int ...A) {
3+
for (int x : A) {
4+
System.out.print(" "+x);
85
}
96
}
10-
117
public static void main(String[] args) {
128
show();
139
show(10,20,30);
1410
show(new int[]{3,4,5,6,7,8,9,10});
1511
//New means created in heap
16-
//No reference it is an anonmous array reference.
12+
//No reference it is an anonymous array reference.
1713
}
1814
}

0 commit comments

Comments
 (0)