I want to know how Integer class works: Consider
Integer number=2;
Does this mean, "Integer" class has a constructor like mentioned below and it stores the int value in it? Please explain.
class Integer
{
int a;
public Integer (int a)
{
this.a=a;
}
}
Pretty close. Check out the source code for Integer (apparently from Harmony so the Sun/Oracle JVM may be a bit different). Autoboxing conversions (when you assign a primitive to a wrapper class) use the equivalent of valueOf, which caches "common" integers and creates new ones for the rest.
javac generates code to call Integer.valueOf(int) which may or may not construct a new Integer or just reuse an existing one. In the JLS this is covered by "boxing conversions".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With