What is the difference between primitive and reference variables in Java?

In Java, variables can be categorized into two types: primitive variables and reference variables. They differ in how they store data and how they interact with memory.

3 Points Compared and Contrasted:

  1. Data Storage:
  2. Primitive Variables:

Directly store the actual data or value in memory.
* Example: int age = 25; stores the integer 25 directly in memory.
3. Reference Variables:

Store a reference (or memory address) that points to an object in memory. They don’t store the actual object data but point to where the object is located.

* Example: `String name = "John";` stores a reference to the `String` object `"John"` in memory, not the actual characters themselves.*Summary:* Primitive variables store values directly, whereas reference variables store memory addresses that point to objects.
  1. Data Types:
  2. Primitive Variables:

Hold one of Java’s 8 primitive types: int, byte, short, long, float, double, char, and boolean.
* Example: int, double, and boolean are primitive types.
3. Reference Variables:

Hold references to objects, including arrays, String, and custom class objects.

* Example: `String`, arrays, and objects from user\-defined classes like `Person` are reference types.*Summary:* Primitive variables work with basic data types, while reference variables work with objects.
  1. Memory Allocation:
  2. Primitive Variables:

Memory for primitives is allocated in the stack. The actual value is stored directly in the stack, making access fast.
* Example: An int variable has its value (e.g., 25) directly in the stack.
3. Reference Variables:

Memory for objects is allocated in the heap, but the reference (pointer) to the object is stored in the stack. The actual object data resides in the heap.

* Example: A `Person` object is stored in the heap, but the reference is stored in the stack.*Summary:* Primitive variables are allocated in the stack, while reference variables point to objects stored in the heap.

Example:

Primitive Variable Example:

int a = 5;  // Directly stores the value 5 in memory

Reference Variable Example:

String name = "John";  // Stores a reference to the String object in memory

Summary of Key Differences:

  • Primitive variables hold basic data types directly, while reference variables hold references to objects.
  • Primitives are stored in the stack, while reference types have objects in the heap.
  • Primitive types have fixed memory sizes, whereas reference types vary depending on the object.

In conclusion, the primary difference lies in how data is stored and accessed. Primitive variables store data directly, while reference variables store a reference to the object’s memory address.