Note that there are some explanatory texts on larger screens.

plurals
  1. POBehavior of method overloading with varargs
    primarykey
    data
    text
    <p>I have two overloaded methods with varargs int and long. When I run a test passing integer it seems to prefer the varargs long method. Whereas, if I make the methods static and run with an integer it seems to prefer the varargs int method. What's going on here?</p> <pre><code>void varargs(int... i){ System.out.println("Inside int varargs"); for(int x : i) System.out.println(x); } void varagrs(long... l){ System.out.println("Inside long varargs"); for(long x : l) System.out.println(x); } static void staticvarargs(int...i) { System.out.println("Inside static int varargs"); for(int x : i) System.out.println(x); } static void staticvarargs(long...l) { System.out.println("Inside static long varargs"); for(long x : l) System.out.println(x); } public static void main(String args[]){ VarArgs va = new VarArgs(); va.varagrs(1); staticvarargs(1); } </code></pre> <p>Output:</p> <p>Inside long varargs 1</p> <p>Inside static int varargs 1</p> <p>EDIT: I should've chosen better method names. There was a typo varargs, varagrs. Thanks zhong.j.yu for pointing that out.</p> <p><strong>Corrected code and expected behavior:</strong></p> <pre><code>void varargs(int... i){ System.out.println("Inside int varargs"); for(int x : i) System.out.println(x); } void varargs(long... l){ System.out.println("Inside long varargs"); for(long x : l) System.out.println(x); } static void staticvarargs(int...i) { System.out.println("Inside static int varargs"); for(int x : i) System.out.println(x); } static void staticvarargs(long...l) { System.out.println("Inside static long varargs"); for(long x : l) System.out.println(x); } public static void main(String args[]){ VarArgs va = new VarArgs(); va.varargs(1); staticvarargs(1); } </code></pre> <p>Output:</p> <p>Inside int varargs 1</p> <p>Inside static int varargs 1</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload