Intern
What is the difference between primitive and reference types?
sobes.tech AI
Answer from AI
Primitive types store the actual data value, while reference types store a reference (memory address) to an object.
Primitive types:
- occupy a fixed amount of memory.
- are passed by value (the value itself is copied).
- are not objects and do not have methods.
- are used for simple data (numbers, characters, boolean values).
// Primitive types in Java
int count = 10; // stores the value 10
boolean isValid = true; // stores the value true
Reference types:
- occupy varying amounts of memory depending on the object.
- are passed by reference (the address of the object is copied).
- are objects and have methods.
- are used for complex data (objects, arrays, strings).
// Reference types in Java
String message = "Hello"; // message stores a reference to a string object in memory
Integer number = 20; // Integer is a wrapper class for the primitive type int, a reference type
Comparison:
| Attribute | Primitive types | Reference types |
|---|---|---|
| Storage | Value | Reference (address) |
| Passing | By value | By reference |
| Memory size | Fixed | Variable |
| OOP | Not objects | Objects |
| Example | int, boolean, char |
String, Object, Array |