Comparison of C Sharp and Java - Language and Features - Expressions and Operators - Boxing and Unboxing

Boxing and Unboxing

Both languages allow automatic boxing and unboxing, i.e. they allow for implicit casting between any primitive types and the corresponding reference types.
In C#, the primitive types are subtypes of the Object type. In Java this is not true; any given primitive type and the corresponding wrapper type have no specific relationship with each other, except for autoboxing and unboxing, which act as syntactic sugar for interchanging between them. This was done intentionally, to maintain backward compatibility with prior versions of Java, in which no automatic casting was allowed, and the programmer worked with two separate sets of types: the primitive types, and the wrapper (reference) type hierarchy.

This difference has the following consequences. First of all, in C#, primitive types can define methods, such as an override of Object's ToString method. In Java, this task is accomplished by the primitive wrapper classes.
Secondly, in Java an extra cast is needed whenever one tries to directly dereference a primitive value, as it will not be boxed automatically. The expression ((Integer)42).toString will convert an integer literal to string in Java while 42.ToString performs the same operation in C#. This is because the latter one is actually an instance call on the primitive value 42, while the former one is an instance call on an object of type java.lang.Integer.

Finally, another difference is that Java makes heavy use of boxed types in generics (see below).

Read more about this topic:  Comparison Of C Sharp And Java, Language and Features, Expressions and Operators

Other articles related to "boxing and unboxing, boxing, unboxing":

C Sharp Syntax - Types - Boxing and Unboxing
... Boxing is the operation of converting a value of a value type into a value of a corresponding reference type ... Boxing in C# is implicit ... Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type ...

Famous quotes containing the word boxing:

    I can entertain the proposition that life is a metaphor for boxing—for one of those bouts that go on and on, round following round, jabs, missed punches, clinches, nothing determined, again the bell and again and you and your opponent so evenly matched it’s impossible not to see that your opponent is you.... Life is like boxing in many unsettling respects. But boxing is only like boxing.
    Joyce Carol Oates (b. 1938)