Java - Varargs Method Overloading

Introduction

You can overload a method with a variable-length argument.

The parameters for the methods must differ in type, order, or number.

Syntax

The following is a valid example of an overloaded max() method:

class Main {
        public static int max(int x, int y) {
        }

        public static int max(int...num) {
        }
}

Rule

Java uses varargs method as the last resort to resolve a method call.

Example

For the following snippet of code, which calls the overloaded method max() with two arguments:

int max = max(12, 13); // which max() will be called?

Java will call the max(int x, int y).

Consider the following code:

class Main {
   public static int max(int...num) {
   }

   public static int max(double...num) {
   }
}

Which version of the max() method will be called for the following statement?

int max = max(); // Which max() to call?

The above statement will generate a compilation time error.

Related Topic