The operators == and != compare object references, so the output is actually “false” and then “true.”
I changed the code like this:
the output are both true.
if Integer n1=47;like Integer n1 = new Integer(47); create an object. n1 and n2 have different reference ,why n1==n2 is true?
because sentence (Integer n1) define n1 as a Integer class.so it can use method equals() to compare n1 and n2 .what does == compare?
what's the different of (Integer n1=47and (Integer n1= new Integer(47)?does the second sentence create an object? and the first one does not?
It's because certain classes like Integer have an object cache for common values.
If you use new Integer(..) then you are requesting a new object but if you use Integer.valueOf(..) or, as you have done, let the compiler provide the conversion from int to Integer then you may get a cached object and hence they are the same.
Joined: Nov 25, 2012
thanks for your help!
if the code like this:
the compile just create a cache to hold the value.no object and reference has been create.the compiler treat n1 and n2 as two primitive type .so n1==n2 is true.
but it can still use method equals to compare their value?
am i right?
Joined: Aug 07, 2007
No, the Integer has a cache that may contain an instance of the Integer with the value you want (ie 47), if it does you get the cached object reference if not you get a new instance object reference. There is no set defined range of values that are cached but on my machine using jdk1.6 on Windows the range is -128 to 127.