sunny ranjan sunny ranjan - 3 months ago 8x
Java Question

What is the difference between (Integer)y and new Integer(y) in java?

It is very helpful to tell me the difference between:

Integer in = (Integer)y;


Integer in = new Integer(y);

I wanted to convert
type to
type and vice versa.

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");

  • Integer in = (Integer)y; is unnecessary casting.
  • Integer in = new Integer(y); The new Integer instance will be created.

You needn't think about. Java does it for you. These processes (conversions between the primitive types and their corresponding object wrapper classes) are called Autoboxing and Unboxing.

The best way (as the compiler does) to do what you want is

Integer i1 = Integer.valueOf(y); // primitive -> reference type 
int i2 = i1.intValue(); // reference type -> primitive

I want to convert int type to Integer type and vice versa.

int i1 = 10;

Integer i2 = i1; // autoboxing 
i1 = i2; // unboxing