I asked:
Is autoboxing/unboxing is done at runtime (JVM) or compile time (compiler)?
I received this answer:
Autoboxing is achieved by the insertion of method calls and casts by the compiler, into the code. These calls and casts are handled at runtime.
Please explain in more detail.
Autoboxing and unboxing are compile time processes.
We can verify with a small test as described below:
Create a Java project, say, with name 'Crap'. Inside that, create a .java file with below contents:
Build this project and export as a jar file, say crap.jar.
Now create one more Java project, say, with name 'Junk'. Add crap.jar file into the classpath of this project and then create a .java file with below contents:
Now, build Junk project, and run Junk.java as Java application. It will run successfully and the output will be
lol.. this is crap!!
Now, modify Crap.java, modify the Boolean crap to boolean and also the corresponding getters and setters. Code will look like as below:
Again build this project and export it as crap.jar. Put this crap.jar file into the classpath of Junk project (and remove the earlier jar file from its classpath).
Now if you try to run Junk.java as java application, you will get below stacktrace:
From Java Specification
Chapter 5. Conversions and Promotions
From here, we know compiler will accept particular expression even if the programmer does not indicate a type conversion. That's why following code does not raise an error at compile time.
Chapter 5. Conversions and Promotions 5.1.7. Boxing Conversion
Chapter 5. Conversions and Promotions 5.1.8. Unboxing Conversion
and this is what happens exactly in run-time.
Well, it says the compiler does it. So it happens at compile time.
This is necessary to ensure the static type safety of Java.