Reputation: 1655
What is the Difference between declaring int's as Below. What are the cases which suits the usage of different Types
int i = 20;
Integer i = 20;
Integer i = new Integer(20);
Please Note : I have goggled and found that first is going to create primitive int.Second is going to carry out auto boxing and Third is going to create reference in memory.
I am looking for a Scenario which clearly explains when should I use first, second and third kind of integer initialization.Does interchanging the usage is going to have any performance hits
Thanks for Reply.
Upvotes: 3
Views: 6575
Reputation: 4202
One such scenario I can think of is when you are mapping DB types in Hibernate
. If you use Integer you can check for null (assuming the column allows null
values). If you use primitive and if the value is null in the database, I guess it throws an error.
Upvotes: 1
Reputation: 719679
The initialization in the 1st case is a simple assignment of a constant value. Nothing interesting... except that this is a primitive value that is being assigned, and primitive values don't have "identity"; i.e. all "copies" of the int
value 20
are the same.
The 2nd and 3rd cases are a bit more interesting. The 2nd form is using "boxing", and is actually equivalent to this:
Integer i = Integer.valueOf(20);
The valueOf
method may create a new object, or it may return a reference to an object that existed previously. (In fact, the JLS guarantees that valueOf
will cache the Integer
values for numbers in the range -128..+127 ...)
By contrast new Integer(20)
always creates a new object.
This issue with new object (or not) is important if you are in the habit of comparing Integer
wrapper objects (or similar) using ==
. In one case ==
may be true
if you compare two instances of "20". In the other case, it is guaranteed to be false
.
The lesson: use .equals(...)
to compare wrapper types not ==
.
On the question of which to use:
i
is int
, use the first form.i
is Integer
, the second form is best ... unless you need an object that is !=
to other instances. Boxing (or explicitly calling valueOf
) reduces the amount of object allocation for small values, and is a worthwhile optimization.Upvotes: 6
Reputation: 5506
Primitives will take default values when declared without assignment.
But wrapper classes are reference types, so without assignment they will be null
. This may cause a NullPointerException
to be thrown if used without assignment.
Upvotes: 3