The variables in Java can be categorized into two types: primitive variables and reference variables
- Primitives A primitive can be one of eight types: char, boolean, byte, short, int, long, double, or float. Once a primitive has been declared, its primitive type can never change, although in most cases its value can change
- Reference variables A reference variable is used to refer to (or access) an object. A reference variable is declared to be of a specific type and that type can never be changed. A reference variable can be used to refer to any object of the declared type, or of a subtype of the declared type (a compatible type)
What are object reference variables?
Objects are instances of classes, including both predefined and user-defined classes. For a reference type in Java, the variable name evaluates to the address of the location in memory where the object referenced by the variable is stored. An object reference is, in fact, a memory address that points to a memory area where an object’s data is located.
Let’s define a class, Person, as follows:
class Person { }
When an object is instantiated with the new operator, a heap-memory address value to that object is returned. That address is usually assigned to the reference variable
When the statement shown in figure executes, three things happen:
- A new Person object is created.
- A variable named person is created in the stack with an empty (null) value.
- The variable person is assigned the memory address value where the object is located.
Reference variables v/s Primitive variables
Just as men and women are fundamentally different (according to John Gray, author of Men Are from Mars, Women Are from Venus), primitive variables and object reference variables differ from each other in multiple ways. The basic difference is that primitive variables store the actual values, whereas reference variables store the addresses of the objects they refer to.
Let’s assume that a class Person is already defined. If you create an int variable a, and an object reference variable person, they will store their values in memory
Nice article, especially those images :)
ReplyDeleteNice and simple with those diagrams
ReplyDelete