2

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;
    }
}
2
  • 2
    No reason to guess what Integer class has. Take a look at the source code yourself kickjava.com/src/java/lang/Integer.java.htm Commented Feb 14, 2011 at 4:50
  • One exception would be Void which doesn't have a public constructor (or a value inside) Commented Feb 14, 2011 at 8:56

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yep it's basically identical, except they used "value" instead of "a". See lines 38, and 83-85
2

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

1 Comment

@ranjanarr Depends upon implementation. It's in the src.zip for the usual Oracle JDKs. The exact code has changed between updates.
1

That means auto boxing is in place.

1 Comment

@rananarr - Take a look at my comment.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.