Intern
What is the difference between primitive and reference data types?
sobes.tech AI
Answer from AI
Primitive types directly store the value, while reference types store a reference (memory address) to an object that contains the value.
Primitive types:
- occupy a fixed and small amount of memory.
- are passed by value (the value itself is copied).
- start with a lowercase letter.
- include:
byte,short,int,long,float,double,boolean,char.
// Example of a primitive type
int a = 10;
int b = a; // copies the value 10
b = 20; // only b changes, a remains 10
Reference types:
- occupy varying amounts of memory depending on the object's content.
- are passed by reference (the address of the object is copied). Changing the object via the reference affects all variables referencing it.
- usually start with a capital letter (classes).
- include: classes (
String,Object, user-defined classes), interfaces, arrays.
// Example of a reference type
String str1 = new String("Hello");
String str2 = str1; // copies the reference to the "Hello" object
str2 = "World"; // str2 now references a new "World" object. str1 still references "Hello".
// Another example with a mutable object
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
ArrayList<Integer> list2 = list1; // copies the reference to the same ArrayList object
list2.add(2); // adds an element to the object accessible via both references
// Now, list1 contains [1, 2] and list2 contains [1, 2]
Brief comparison table:
| Property | Primitive types | Reference types |
|---|---|---|
| Storage | Value | Reference to object |
| Passing | By value | By reference |
| Memory size | Fixed | Variable |
| Starts with | Lowercase letter | Usually uppercase letter |
| Nullability | Cannot be null |
Can be null |
Primitive types are wrapped in corresponding wrapper classes (e.g., int in Integer) to work with them as objects.