3.2.2 Reference Data Types (Strings, Objects)
3.2.2 Reference Data Types (Strings, Objects)
While primitive data types store simple, direct values, Reference Data Types are a bit different. Imagine instead of putting the actual item in a box, you put a map or an address to where the item is stored in a much bigger warehouse.
Reference Data Types (often called "objects" in programming) don't store the actual data directly. Instead, they store a "reference" or a "memory address" that tells the computer where to find the actual data. The actual data (the object) is stored in a different, larger part of the computer's memory called the "heap."
Here are common reference data types:
- Strings (Sequences of Characters/Text):
- While a
char
holds a single letter, a String holds a whole sequence of characters, like a word, a sentence, or a paragraph. - Examples:
"Hello World"
,"My name is Alex"
,"123 Main Street"
. (Notice they are usually put in double quotes). - Strings are incredibly common for storing names, addresses, messages, and any kind of text information.
- In many languages (like Java), Strings are actually special kinds of objects, not primitive types.
- While a
- Objects (Instances of Classes):
- Remember Classes from Object-Oriented Programming? A class is like a blueprint. When you build something from that blueprint, you create an Object.
- A reference data type variable for an object will hold the memory address of that specific object.
- Examples:
- If you have a
Car
blueprint (class), thenmyRedCar
could be an object of typeCar
. ThemyRedCar
variable would hold the address of where that specific red car's details (color, speed, etc.) are stored in memory. - A
Dog
object, aBankAccount
object, aGameCharacter
object.
- If you have a
- These objects can be very complex, holding many pieces of data (properties) and having many actions they can perform (methods).
Key Difference from Primitive Types: When you copy a primitive type, you copy the value. When you copy a reference type, you copy the address. This means if two reference variables hold the same address, they are both pointing to and can change the same exact object.
Bibliography:
- GeeksforGeeks - Primitive vs Reference Data Types in Java: https://www.geeksforgeeks.org/java/java-data-types/
- Oracle Java Documentation - Data Types: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html (More advanced, but good for reference)
- Wikipedia - Reference type: https://en.wikipedia.org/wiki/Reference_type