Course contentsShow
← Java
Lesson 221 of 2,8705. Methods and Function CallsFree lesson

Empty Varargs and Null Handling

Learn how varargs handle the case of zero arguments, creating an empty array, and how null is treated differently.

Empty Varargs and Null Handling

What you'll learn: How varargs behave when you pass zero arguments or null, and why Java treats these cases differently.


What Happens with Zero Arguments?

When you call a varargs method without passing any arguments at all, Java doesn't give up—it simply creates an empty array behind the scenes. The method receives an array with length zero, not null.

Think of varargs like an automatic bag collector: even if you put nothing in the bag, the bag itself still exists—it's just empty.

public static void printItems(String... items) {
    System.out.println("Array length: " + items.length);
}

// Calling with zero arguments
printItems();  // Prints: Array length: 0

The items parameter is a real array with length = 0, so you can safely call .length or loop through it without a NullPointerException.


What About Passing null?

Here's where it gets tricky. If you explicitly pass null, Java treats it as a null array reference, not an empty array:

printItems(null);  // items will be null, not an empty array!

Inside the method, items would be null, and calling items.length would throw a NullPointerException. You must handle this case if your method might receive an explicit null:

public static void printItems(String... items) {
    if (items == null) {
        System.out.println("Received null");
        return;
    }
    System.out.println("Array length: " + items.length);
}

Why the Difference?

Zero arguments means "create an empty container." Passing null means "here's a null container." Java respects the explicit null you provide but protects you when you simply omit arguments.

Key Takeaway: Varargs with zero arguments creates an empty array (length 0), but explicitly passing null gives you a null reference—handle both cases defensively when necessary.