Question

The following code compiles fine in Java:

public static void main(String[] args) {
    int i =5;
    call(i);
}


static void call(int i){
    System.out.println("int");
}

static void call(long i){
    System.out.println("long");
}

static void call(Integer i){
    System.out.println("Integer");
}


static void call(Object i){
    System.out.println("Object");
}

But the following code gives compile time error:

public static void main(String[] args) {
    int i =5;
    call(i);
 }


static void call(int... i){
    System.out.println("int...");
}

static void call(long... i){
    System.out.println("long...");
}

static void call(Integer... i){
    System.out.println("Integer...");
}


static void call(Object... i){
    System.out.println("Object...");
}

Why the similar call mechanism is not maintained by Java while working with var-args? In the second example also, the call should go to method static void call(int... i)

Was it helpful?

Solution 4

OTHER TIPS

Here is answer

Java doesnot work well with overloading varargs method.

Here is what Specs provide :

So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

As you are declaring the method as Static void call(int... i) and the method expects the int array but while calling this method you are sending only one integer value.

Static void call(int... i) is Same as Static void call(int[] i)

Variable arguments are treated as arrays in java. So instead of passing an int value, pass it like an array . For eg.

int[] i ={5};
call(i);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top