Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Autoboxing did not work in Annonymous class in java

What can be the reason for this to not work?

ThreadLocal<Integer> intLocal2 = new ThreadLocal<>() {
            @Override
            protected int initialValue() { // if I use int as return type it doesn't work
                return 0;
            }
        };

but if I use Integer as return type of initialValue() it will work.

I tried this on java 11

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Autoboxing is impossible for the return types, see the docs:
https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Converting a primitive value (an int, for example) into an object of
the corresponding wrapper class (Integer) is called autoboxing. The
Java compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the
    corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading