ranjanarr
ranjanarr

Reputation: 153

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;
    }
}

Upvotes: 2

Views: 570

Answers (4)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

You can always find the latest OpenJDK Integer class here:

The relevant field is (from line 645):

/**
 * The value of the {@code Integer}.
 *
 * @serial
 */
private final int value;

Upvotes: 0

Steven Schlansker
Steven Schlansker

Reputation: 38526

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.

Upvotes: 6

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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

Upvotes: 2

Aravind Yarram
Aravind Yarram

Reputation: 80176

That means auto boxing is in place.

Upvotes: 1

Related Questions