Unlike C# (I think), there's a difference between "int" and "Integer. Integer is a class, while "int" is a primitive. Due to auto-boxing you can create an Integer object from an int, but it will still remain an object.
The problem is caused by him comparing objects as if they were primitives. The Integer class is basically just a wrapper around an "int" primitive. When an Integer object is initialized with a value between -128 and 127 it will return an object from an internal cache.
The second time he creates an Integer with the value of 127 it uses the cached object, which of course is identical to the previous one. When he tries this with 128, the cache is not used and a new Integer object is created.
tl;dr; Integer is an object where some values are cached to avoid creating a new object. The "==" operator compares the objects, and not the values they represent.
It's the same in C#, == is used for reference comparison, you use it when you want to know whether two objects are the same object, whereas you would typically use .Equals() for value comparison.
There is no wrapper class for "primitives" in C# though, to box it, you cast it to System.Object, and that allocates an object instance for you on the heap. To unbox, cast it to System.Int32.
'int' in C# is just an alias for System.Int32 though, so I guess there is no analogue to the Java situation in C#. You'd either be comparing System.Object references, or System.Int32 value types, not some hybrid.
3 comments
[ 3.5 ms ] story [ 17.4 ms ] threadNow you have to carry around the fact that == sometimes isn't a reference comparison, even though that's what Java claims it always is?
Seems like a pretty poor design decision.
If I'm missing something basic, please correct away.
The problem is caused by him comparing objects as if they were primitives. The Integer class is basically just a wrapper around an "int" primitive. When an Integer object is initialized with a value between -128 and 127 it will return an object from an internal cache.
The second time he creates an Integer with the value of 127 it uses the cached object, which of course is identical to the previous one. When he tries this with 128, the cache is not used and a new Integer object is created.
tl;dr; Integer is an object where some values are cached to avoid creating a new object. The "==" operator compares the objects, and not the values they represent.
There is no wrapper class for "primitives" in C# though, to box it, you cast it to System.Object, and that allocates an object instance for you on the heap. To unbox, cast it to System.Int32.
'int' in C# is just an alias for System.Int32 though, so I guess there is no analogue to the Java situation in C#. You'd either be comparing System.Object references, or System.Int32 value types, not some hybrid.
Example:
Prints: