Junior
What is the difference between an object and a primitive in Java?
sobes.tech AI
Answer from AI
In Java, entities can be divided into two categories: primitive data types and reference types (objects).
Primitive data types:
- Store the actual data value in memory.
- Have a fixed size in memory.
- Cannot be
null. - Eight built-in primitive types:
byte(integer)short(integer)int(integer, most commonly used)long(integer)float(single-precision floating point)double(double-precision floating point, most commonly used)boolean(logical)char(character)
Objects:
- Are instances of classes.
- Store references to data, not the data itself. Data is stored in the heap.
- Have a variable size in memory (depends on the content of the object).
- Can be
null, which means no reference to an object in memory. - Objects have methods and fields (data).
- Are created using the
newkeyword (except for strings created as literals).
Comparison:
| Characteristic | Primitive | Object |
|---|---|---|
| Data storage | The actual value | Reference to the value (in the heap) |
| Size in memory | Fixed | Variable |
null possibility |
No | Yes |
| Methods and fields | No | Yes |
| Creation | Declaration (e.g., int x;) |
Using new (explicit or implicit) |
| Passing to methods | By value (copy of the value) | By reference (copy of the reference, same object) |
Example:
// Primitive: variable 'a' stores the actual value 10
int a = 10;
// Object: variable 'str' stores a reference to a String object in the heap
String str = new String("Hello");
// Primitive cannot be null
// int b = null; // Compilation error
// Object can be null
String nullStr = null;