What is the difference between boxing/unboxing and type casting?

Boxing refers to a conversion of a non-nullable-value type into a reference type or the conversion of a value type to some interface that it implements (say int to IComparable<int>). Further, the conversion of an underlying value type to a nullable type is also a boxing conversion. (Caveat: Most discussions of this subject will ignore … Read more

Comparing boxed value types

If you need different behaviour when you’re dealing with a value-type then you’re obviously going to need to perform some kind of test. You don’t need an explicit check for boxed value-types, since all value-types will be boxed** due to the parameter being typed as object. This code should meet your stated criteria: If value … Read more

Method overload resolution in java

The compiler will consider not a downcast, but an unboxing conversion for overload resolution. Here, the Integer i will be unboxed to an int successfully. The String method isn’t considered because an Integer cannot be widened to a String. The only possible overload is the one that considers unboxing, so 8 is printed. The reason … Read more

Integer wrapper class and == operator – where is behavior specified? [duplicate]

Because of this code in Integer.valueOf(int): public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); } Explanation: Integer integer1 = 127 is a shortcut for Integer integer1 = Integer.valueOf(127), and for values between -128 and 127 (inclusive), the Integers are put in a … Read more

What is boxing and unboxing and what are the trade offs?

Boxed values are data structures that are minimal wrappers around primitive types*. Boxed values are typically stored as pointers to objects on the heap. Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive. Obviously this … Read more

How does auto boxing/unboxing work in Java?

When in doubt, check the bytecode: Integer n = 42; becomes: 0: bipush 42 2: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 5: astore_1 So in actuality, valueOf() is used as opposed to the constructor (and the same goes for the other wrapper classes). This is beneficial since it allows for caching, and doesn’t force the creation … Read more