Forum Stats

  • 3,735,165 Users
  • 2,247,124 Discussions
  • 7,857,754 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,863
    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.

  • nihitthakkar
    nihitthakkar Member Posts: 121 Blue Ribbon

    Autoboxing: Converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is:

    1. Passed as a parameter to a method that expects an object of the corresponding wrapper class.

    2. Assigned to a variable of the corresponding wrapper class.


    Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int. The Java compiler applies unboxing when an object of a wrapper class is:

    1. Passed as a parameter to a method that expects a value of the corresponding primitive type.

    2. Assigned to a variable of the corresponding primitive type.


    // Java program to illustrate the concept

    // of Autoboxing and Unboxing

    import java.io.*;

      

    class GFG

    {

      public static void main (String[] args)

      {

        // creating an Integer Object

        // with value 10.

        Integer i = new Integer(10);

      

        // unboxing the Object

        int i1 = i;

      

        System.out.println("Value of i: " + i);

        System.out.println("Value of i1: " + i1);

      

        //Autoboxing of char

        Character gfg = 'a';

      

        // Auto-unboxing of Character

        char ch = gfg;

        System.out.println("Value of ch: " + ch);

        System.out.println("Value of gfg: " + gfg);

      

      }

    }

    Output:


    Value of i: 10

    Value of i1: 10

    Value of ch: a

    Value of gfg: a

Sign In or Register to comment.