Value type and reference type
In certain computer programming languages, data types are classified as either value types or reference types, where reference types are always implicitly accessed via references, whereas value type variables directly contain the values themselves.
Properties of value types and reference types
Even among languages that have this distinction, the exact properties of value and reference types vary from language to language, but typical properties include:- Primitive data types, such as Booleans, fixed-size integers, floating-point values, and characters, are value types.
- Objects, in the sense of object-oriented programming, belong to reference types.
- Assigning to a variable of reference type simply copies the reference, whereas assigning to a variable of value type copies the value. This applies to all kinds of variables, including local variables, fields of objects, and array elements. Likewise when calling a function: parameters of reference type are copies of the reference, whereas parameters of value type are copies of the value.
- If a reference type is mutable, then mutations made via one reference are visible via any other, whereas if a value type is immutable, then mutations made to one value are not visible in another.
- Reference types support the notion of identity — it makes sense to discuss whether two values of reference type refer to the same object, and the language provides functionality to determine whether they do — whereas value types do not.
- Values of reference type refer to objects allocated in the heap, whereas values of value type are contained either on the call stack or inside their containing entities.
- Reference types support the notion of subtyping, whereby all values of a given reference type are automatically values of a different reference type. Value types do not support subtyping, but may support other forms of implicit type conversion, e.g. automatically converting an integer to a floating-point number if needed. Additionally, there may be implicit conversions between certain value and reference types, e.g. "boxing" a primitive into an object, or reversing this via "unboxing".