Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper class in java is it a class with primitive data type as member?

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;
    }
}
like image 214
ranjanarr Avatar asked Dec 07 '25 06:12

ranjanarr


2 Answers

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.

like image 114
Steven Schlansker Avatar answered Dec 09 '25 18:12

Steven Schlansker


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".

like image 34
Tom Hawtin - tackline Avatar answered Dec 09 '25 18:12

Tom Hawtin - tackline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!