Autoboxing int Integer — oracle-tech

    Forum Stats

  • 3,681,447 Users
  • 2,238,013 Discussions
  • 7,831,224 Comments

Discussions

Autoboxing int Integer

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

  • jwentingjwenting Posts: 4,863
    edited January 7

    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.

Sign In or Register to comment.