What is the difference between the following:
Integer in = (Integer)y;
and
Integer in = new Integer(y);
I want to convert int
type to Integer
type and vice versa. Here is my code for doing that:
public class CompareToDemo {
public static void main(String[] args) {
// Integer x=5;
int y=25;
System.out.println(y+" this is int variable");
Integer in = (Integer)y;
//Integer in = new Integer(y);
if(in instanceof Integer){
System.out.println(in +" this is Integer variable");
}
}
}
If all you want to do is to convert an int
primitive to an Integer
object,
you have four options
Integer in = (Integer)y; // 1 explicit cast
Integer in = y; // 2 implicit cast (autoboxing)
Integer in = new Integer(y); // 3 explicit constructor
Integer in = Integer.valueOf(y); // 4 static factory method
The most preferable way here is 2 (autoboxing). The explicit constructor (3) is the less preferable, as it might have some small performance hit.
Also, they are not strictly equivalent. Consider:
public static void main(String[] args) {
int x = 25;
Integer a = new Integer(x);
Integer b = new Integer(x);
System.out.println(a == b); // false
Integer c = Integer.valueOf(x);
Integer d = Integer.valueOf(x);
System.out.println(c == d); // true
Integer e = (Integer)x;
Integer f = (Integer)x;
System.out.println(e == f); // true
}
This is because small integers are cached (details here).