Middle
What are reference types arrays?
sobes.tech AI
Answer from AI
Arrays of reference types are data structures that store not the objects themselves, but references to them in memory. Each element of the array is a pointer to the location of an object in the "heap".
Key features:
- Store references: Array elements store addresses of objects.
- Object creation: Objects referenced by the array are created separately using the
newoperator. The array itself is also created withnew. - Default value: For reference type array elements, the default value is
nullif no other value is assigned. This means the reference points "nowhere". - Dynamic size: Although the array itself has a fixed size after creation, the objects it references can be dynamic (e.g., strings or lists).
Example in Java:
// Creating an array of reference type String
String[] names = new String[3];
// Assigning references to String objects
names[0] = new String("Alice");
names[1] = "Bob"; // String literals also create objects
// Default value for uninitialized elements
// names[2] is `null` by default
// Accessing objects via references
int lengthOfFirstName = names[0].length();