Junior
What are reference data types?
sobes.tech AI
Answer from AI
Reference data types store not the actual value, but a reference (memory address) to the location where the value is stored.
Features:
- Variables of reference type can hold a
nullreference. - When assigning the value of one reference type variable to another, the reference is copied, not the actual value. Both variables then point to the same memory location.
- Changes made through one reference will be visible through the other if they point to the same object.
- Memory for reference type objects is managed by the garbage collector.
Examples of reference data types:
- Strings (
String) - Arrays
- Objects of user-defined classes
- Delegates (in some languages)
Difference from value types:
| Characteristic | Value types | Reference types |
|---|---|---|
| Storage | The actual value | A reference to the value |
| Copying | The actual value is copied | The reference is copied |
| Modification | Changes in the copy do not affect the original | Changes through one reference are visible through another (if they point to the same object) |
| Memory | Managed by the stack (usually) | Managed by the heap, cleaned up by the garbage collector |
| Examples | int, float, bool, struct (in some languages) |
String, Array, Object |
// Example in C#
string s1 = "Hello"; // s1 holds a reference to the string "Hello"
string s2 = s1; // s2 now holds the same reference as s1
// Changes will not be visible through the other reference,
// because strings in C# are immutable.
// When changed, a new string is created and the reference is reassigned.
s1 = "World";
Console.WriteLine(s2); // Outputs "Hello"
int[] arr1 = { 1, 2, 3 }; // arr1 holds a reference to the array {1, 2, 3}
int[] arr2 = arr1; // arr2 now holds the same reference
arr2[0] = 10; // Change through arr2
Console.WriteLine(arr1[0]); // Outputs 10, change is visible through arr1
// Example in Java
String s1 = "Hello"; // s1 holds a reference to the string "Hello"
String s2 = s1; // s2 now holds the same reference as s1
// Strings in Java are immutable.
// When changed, a new string is created and the reference is reassigned.
s1 = "World";
System.out.println(s2); // Outputs "Hello"
int[] arr1 = { 1, 2, 3 }; // arr1 holds a reference to the array {1, 2, 3}
int[] arr2 = arr1; // arr2 now holds the same reference
arr2[0] = 10; // Change through arr2
System.out.println(arr1[0]); // Outputs 10, change is visible through arr1