Varargs (Variable Arguments) & Internal Array Allocation
1Concept
Varargs (type... args) allows methods to accept zero or more arguments. Under the hood, the compiler allocates an array of the specified type before invoking the method bytecode (`invokevirtual`). Varargs must always be the last parameter in the method signature.
2Architecture Diagram
Method Call: calculateTotal("Invoice", 10, 20, 30)
|
v javac bytecode transformation:
calculateTotal("Invoice", new int[]{10, 20, 30}) ---> Creates Array on Heap!3Code Example
Core Java
public class VarargsDemo {
public static double computeAverage(String category, double... scores) {
System.out.println("Category: " + category + " | Count: " + scores.length);
if (scores.length == 0) return 0.0;
double sum = 0;
for (double score : scores) sum += score;
return sum / scores.length;
}
public static void main(String[] args) {
double avg1 = computeAverage("Performance Ratings", 94.5, 88.0, 96.2);
System.out.printf("Computed Average: %.2f%n", avg1);
// Zero-argument varargs call
double avg2 = computeAverage("Empty Batch");
System.out.println("Empty Batch Average: " + avg2);
}
}4Expected Output
Category: Performance Ratings | Count: 3 Computed Average: 92.90 Category: Empty Batch | Count: 0 Empty Batch Average: 0.0
5Key Takeaways
- ✓Every varargs invocation creates a new heap array; avoid in high-throughput hot loops.
- ✓Only ONE varargs parameter is permitted, and it MUST be the final parameter in the signature.
- ✓Passing null to varargs can cause NullPointerException or ambiguous resolution.