Reputation: 153
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
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
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
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