1

I'm a newbie to programming. Tell me the difference between Integer x= 59; and Integer x= new Integer (59); They both do the same thing basically and I'm getting the output either way.

public class WrapperClass
{
    public static void main(String args[]) 
    {
        Integer x= 59; // 
        byte y= x.byteValue();
        System.out.println(y);
    }
}

and

public class WrapperClass
{
    public static void main(String args[]) 
    {
        Integer x = new Integer (10);
        byte y= x.byteValue();
        System.out.println(y);
    }
}
Srinu Chinka
  • 1,471
  • 13
  • 19

1 Answers1

6

Not much difference. Autoboxing ( Integer x = 59;) will call Integer.valueOf( 59 ); while the other method calls the constructor. Has minor implications for caching (valueOf might give the same object reference for two equal values, new will not), but not much more.

And just to make sure: Autoboxing/valueOf MIGHT give you the same object reference when calling it two times with two equal values (at least if your values are between -128 an 127), but that still makes it a very, very bad idea to compare two Integer objects via ==.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58