Forum Stats

  • 3,769,556 Users
  • 2,252,976 Discussions
  • 7,875,083 Comments

Discussions

Autoboxing int Integer

2934488
2934488 Member Posts: 8

Hi,

I am preparing for the exam.

I need help to understand why in this code the int method is chosen, I have tested only with Integer and that one is also executed:

public class Teststuff {

            public static void doSum(Integer x, Integer y){

          System.out.println("Integer sum is "+(x+y));

      }

    

      public static void doSum(int x, int y){

          System.out.println("int sum is "+(x+y));

      }

     

   

    public static void main(String[] args) {

        doSum(10, 20);

}

}

Thank you!

Answers

  • jwenting
    jwenting Member Posts: 4,864 Gold Badge
    edited Jan 7, 2020 1:56AM

    Just try to reason which method would be the closest match, and the answer becomes quite obvious.

    There is of course a potential for ambiguity, and that's if you try to call for example doSum(10, Integer.valueOf(20));

    I've not tried what would happen in that case, I'd not be surprised if it'd lead to a compiler error.