H. Riantsoa
H. Riantsoa

Reputation: 89

How JVM treats reference variables?

Just want to know whether this statement is true or not:

For these lines of code:

Person Bob = new Person("Bob W.", 30);
System.out.println(Bob.name);

An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable . Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. Then JVM looks at Bob's name and prints it!

Thanks!

Upvotes: 1

Views: 267

Answers (1)

flakes
flakes

Reputation: 23584

All objects in Java are accessed via their references (different from primitive access!). The variable bob is a reference to an instance of the Person class. Memory allocation/disposal of instances will be handled by the JVM, and the instance data will be kept alive by the JVM as long as there exist strong references to that instance (ie Person bob = new ... declares a strong reference to the newly created Person instance).

An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable

It would be more correct to say that an "An instance of the Person Object is created", but yes, all variables used for objects in Java are reference variables. Calling new will return the reference to the instance created. There can be many reference variables which point to a single instance. For example, in the following code snippet we can have two references pointing to a single instance:

Person bob = new Person("Bob W.", 30);
Person bob2 = bob;

Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object.

Exactly. After code is compiled, the JVM bytecode will use the instruction getfield to access the name field. This instruction requires an object reference and the field reference. In this case bob.name will use bob as the objectref and use Person#name as the fieldref.

Upvotes: 2

Related Questions