Briefly speaking,
- The line Integer in = (Integer)y;uses an unnecessary cast.
- The line Integer in = new Integer(y);creates anIntegerinstance.
Each case in detail
First, let's consider the case with explicit casting.
Integer i = (Integer)10;
The compiler understands that 10 is an int primitive type and the fact that it has to be wrapped by its Integer to make it compiles. It seems javac will make the following:
Integer i = (Integer)Integer.valueOf(10);
But the compiler is smart enough to do unnecessary casting, (Integer) just will be omitted:
Integer i = Integer.valueOf(10);
Next, there is the case with instance creation.
Integer i = new Integer(10);
Here is all simply. A new instance of Integer class will be created anyway. But, as the documentation says, usually, it is not appropriate way:
It is rarely appropriate to use these constructors. The static factories valueOf() are generally a better choice, as it is likely to yield significantly better space and time performance.
Conclusion
In everyday code writing, we usually use autoboxing and unboxing. They are automatic conversions between the primitive types and their corresponding object wrapper classes (has been introduced in Java 5). So you needn't think much about Xxx.valueOf(xxx) and .xxxValue() methods. It is so convenient, isn't it?
Integer i = 10; // autoboxing
int j = i; // unboxing