BCA / B.Tech 9 min read

Reference Variables

Reference Variables in Java:

In Java, variables are divided into two main categories: primitive variables and reference variables.

  • Primitive Variable: Stores the actual value of the data directly in the memory location allocated to it (e.g., `int x = 10;`).
  • Reference Variable: Does not store the actual object data, but instead stores the memory address (or a "reference") of where the object is located in the heap memory. All variables of non-primitive types (Classes, Interfaces, Arrays, Strings) are reference variables.

Example:

Car myCar = new Car();

In this line, `myCar` is a reference variable. The `new Car()` part creates a new `Car` object in the heap memory, and the memory address of this object is stored in the `myCar` variable.


Key Points:
  • When you assign one reference variable to another (e.g., `Car anotherCar = myCar;`), you are not copying the object. Instead, you are copying the memory address, so both variables now point to the exact same object.
  • A reference variable can be assigned the value `null`, which indicates that it is not currently referring to any object. Attempting to use a `null` reference will result in a `NullPointerException`.