In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to practical disciplines (includi ...
, boxing (a.k.a. wrapping) is the transformation of placing a primitive type within an object so that the value can be used as a
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
. Unboxing is the reverse transformation of extracting the primitive value from its wrapper object. Autoboxing is the term for automatically applying boxing and/or unboxing transformations as needed.
Boxing
Boxing's most prominent use is in
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
where there is a distinction between
reference
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
and
value types for reasons such as runtime efficiency and syntax and semantic issues. In Java, a can only store values of type . One might desire to have a of , but this is not directly possible. Instead Java defines
primitive wrapper class In object-oriented programming, a wrapper class is a class (computer programming), class that Encapsulation (computer programming), encapsulates data type, types, so that those types can be used to create object (computer science), object instance ( ...
es corresponding to each
primitive type
In computer science, primitive data types are a set of basic data types from which all other data types are constructed. Specifically it often refers to the limited set of data representations in use by a particular processor, which all compiled pr ...
: and , and , and , etc. One can then define a using the boxed type and insert values into the list by boxing them as objects. (Using
generic
Generic or generics may refer to:
In business
* Generic term, a common name used for a range or class of similar things not protected by trademark
* Generic brand, a brand for a product that does not have an associated brand or trademark, other ...
parameterized types introduced in
J2SE 5.0, this type is represented as .)
On the other hand,
C# has no primitive wrapper classes, but allows boxing of any value type, returning a generic reference. In
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
, any primitive value can be prefixed by a to make an out of it (e.g. or ). This allows for adding them in any of the standard collections, such as an .
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
has little or no notion of
reference type In computer programming, data types can be divided into two categories: value types (or by-value types) and reference types (or by-reference types). Value types are completely represented by their meaning, while reference types are references to ano ...
, but still uses the term "boxed" for the runtime system's uniform pointer-to-
tagged union
In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...
representation.
The boxed object is always a copy of the value object, and is usually
immutable. Unboxing the object also returns a copy of the stored value. Repeated boxing and unboxing of objects can have a severe performance impact, because boxing
dynamically allocates new objects and unboxing (if the boxed value is no longer used) then makes them eligible for
garbage collection
Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclabl ...
. However, modern garbage collectors such as the default Java HotSpot garbage collector can more efficiently collect short-lived objects, so if the boxed objects are short-lived, the performance impact may not be severe.
In some languages, there is a direct equivalence between an unboxed primitive type and a reference to an immutable, boxed object type. In fact, it is possible to substitute all the primitive types in a program with boxed object types. Whereas assignment from one primitive to another will copy its value, assignment from one reference to a boxed object to another will copy the reference value to refer to the same object as the first reference. However, this will not cause any problems, because the objects are immutable, so there is semantically no real difference between two references to the same object or to different objects (unless you look at physical equality). For all operations other than assignment, such as arithmetic, comparison, and logical operators, one can unbox the boxed type, perform the operation, and re-box the result as needed. Thus, it is possible to not store primitive types at all.
Autoboxing
Autoboxing is the term for getting a reference type out of a value type just through
type conversion
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another. An example would be the conversion of an integer value into a floating point valu ...
(either implicit or explicit). The compiler automatically supplies the extra source code that creates the object.
For example, in versions of Java prior to J2SE 5.0, the following code did not compile:
Integer i = new Integer(9);
Integer i = 9; // error in versions prior to 5.0!
Compilers prior to 5.0 would not accept the last line. are reference objects, on the surface no different from , , and so forth. To convert from an to an , one had to "manually" instantiate the Integer object. As of J2SE 5.0, the compiler will accept the last line, and automatically transform it so that an Integer object is created to store the value .
oracle.com Java language guide entry on autoboxing
/ref> This means that, from J2SE 5.0 on, something like , where and are themselves, will compile now - a and b are unboxed, the integer values summed up, and the result is autoboxed into a new , which is finally stored inside variable . The equality operators cannot be used this way, because the equality operators are already defined for reference types, for equality of the references; to test for equality of the value in a boxed type, one must still manually unbox them and compare the primitives, or use the method.
Another example: J2SE 5.0 allows the programmer to treat a collection (such as a ) as if it contained values instead of objects. This does not contradict what was said above: the collection still only contains references to dynamic objects, and it cannot list primitive types. It cannot be a , but it must be a instead. However, the compiler automatically transforms the code so that the list will "silently" receive objects, while the source code only mentions primitive values. For example, the programmer can now write and think as if the were added to the list; but, the compiler will have actually transformed the line into .
Automatic unboxing
With automatic unboxing the compiler automatically supplies the extra source code that retrieves the value out of that object, either by invoking some method on that object, or by other means.
For example, in versions of Java prior to J2SE 5.0, the following code did not compile:
Integer k = new Integer(4);
int l = k.intValue(); // always okay
int m = k; // would have been an error, but okay now
C# doesn't support automatic unboxing in the same meaning as Java, because it doesn't have a separate set of primitive types and object types. All types that have both primitive and object version in Java, are automatically implemented by the C# compiler as either primitive (value) types or object (reference) types.
In both languages, automatic boxing does not downcast automatically, i.e. the following code won't compile:
C#:
int i = 42;
object o = i; // box
int j = o; // unbox (error)
Console.WriteLine(j); // unreachable line, author might have expected output "42"
Java:
int i = 42;
Object o = i; // box
int j = o; // unbox (error)
System.out.println(j); // unreachable line, author might have expected output "42"
Type helpers
Modern Object Pascal
Object Pascal is an extension to the programming language Pascal that provides object-oriented programming (OOP) features such as classes and methods.
The language was originally developed by Apple Computer as ''Clascal'' for the Lisa Worksh ...
has yet another way to perform operations on simple types, close to boxing, called type helpers in FreePascal
Free Pascal Compiler (FPC) is a compiler for the closely related programming-language dialects Pascal and Object Pascal. It is free software released under the GNU General Public License, witexception clausesthat allow static linking against it ...
or record helpers in Delphi and FreePascal
Free Pascal Compiler (FPC) is a compiler for the closely related programming-language dialects Pascal and Object Pascal. It is free software released under the GNU General Public License, witexception clausesthat allow static linking against it ...
in Delphi mode.
The dialects mentioned are Object Pascal compile-to-native languages, and so miss some of the features that C# and Java can implement. Notably run-time type inference
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
on strongly typed variables.
But the feature is related to boxing.
It allows the programmer to use constructs like
uses sysutils; // this unit contains wraps for the simple types
var
x:integer=100;
s:string;
begin
s:= x.ToString;
writeln(s);
end.
References
{{Data types
Data types
Java (programming language)
Programming language concepts