1. The Hook (The "Byte-Sized" Intro)
- In a Nutshell: Varargs (variable arguments) let methods accept any number of arguments. Internally, Java converts them to an array.
- Syntax: Type... name.
When Slack sends messages to multiple channels: sendTo("Hello", channel1, channel2, channel3...). Any number of recipients!
2. Conceptual Clarity
š” The Analogy: Pizza Toppings
- Regular param = Fixed toppings (cheese, sauce)
- Varargs = "Add any toppings you want..."
- Internally = All toppings become an array
3. Technical Rules
| Rule | Example |
|---|---|
| Only one varargs per method | void m(int... a, int... b) ā |
| Must be last parameter | void m(int... a, String s) ā |
| Can pass array directly | sum(new int[]{1, 2, 3}) ā
|
| Can pass zero arguments | sum() ā
|
4. Interactive & Applied Code
public class VarargsDemo {
public static void main(String[] args) {
// === BASIC VARARGS ===
System.out.println(sum(1, 2, 3)); // 6
System.out.println(sum(1, 2, 3, 4, 5)); // 15
System.out.println(sum()); // 0 (empty)
// === PASS ARRAY ===
int[] numbers = {10, 20, 30};
System.out.println(sum(numbers)); // 60
// === MIXED PARAMETERS ===
greet("Hello", "Alice", "Bob", "Charlie");
// === PRINT ALL (like System.out.printf) ===
printAll("Values:", 1, 2, 3);
// === REAL-WORLD: Logger ===
log("Error", "File not found", "path=/home/user", "code=404");
// === REAL-WORLD: String join ===
String result = join("-", "a", "b", "c");
System.out.println(result); // "a-b-c"
}
// Basic varargs
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) { // Treat as array
total += n;
}
return total;
}
// Varargs with regular parameter (varargs MUST be last)
static void greet(String greeting, String... names) {
for (String name : names) {
System.out.println(greeting + ", " + name + "!");
}
}
// Print any number of objects
static void printAll(String prefix, Object... items) {
System.out.print(prefix + " ");
for (Object item : items) {
System.out.print(item + " ");
}
System.out.println();
}
// Real-world: Logging with context
static void log(String level, String message, String... context) {
System.out.print("[" + level + "] " + message);
if (context.length > 0) {
System.out.print(" | Context: ");
System.out.print(String.join(", ", context));
}
System.out.println();
}
// Join with delimiter
static String join(String delimiter, String... parts) {
return String.join(delimiter, parts);
}
}ā ļø Common Mistakes
Mistake #1: Varargs not last
void method(int... nums, String s) { } // ā Compile error!
void method(String s, int... nums) { } // ā
CorrectMistake #2: Multiple varargs
void method(int... a, String... b) { } // ā Only one allowed!Mistake #3: Null ambiguity
printAll(null); // Ambiguous! Is null the array or an element?
printAll((Object[]) null); // ā
Explicit cast5. The "Interview Corner"
š Q1: "How does varargs work internally?"
Answer: Compiler converts method(1, 2, 3) to method(new int[]{1, 2, 3}). Varargs is syntactic sugar for array parameter.
š Q2: "Varargs vs Array parameter?" Answer:
- Varargs:
sum(1, 2, 3)orsum(arr) - Array:
sum(arr)only Varargs is more flexible at call site.
š Q3: "What if varargs method overloaded?"
Answer: Compiler prefers exact match. method(int) chosen over method(int...) for single arg. Can cause ambiguity warnings.
š Key Takeaways
ā
Syntax: Type... paramName
ā
Must be last parameter
ā
Only one varargs per method
ā
Internally becomes array
ā
Can pass zero to N arguments
ā
Common in printf, String.format, builders