|
In CS170, you have learned that a reference variable is defined as follows:
BankAccount Mary; // Mary is a reference variable String s; // s is a reference variable |
What exactly is a reference variable ???
|
|
|
Example: a variable containing the address 1 will point to memory location 1
|
Example: a variable containing the address 4 will point to memory location 4
In CS170, you have learned that a reference variable is defined as follows:
BankAccount Mary; // Mary is a reference variable String s; // s is a reference variable |
What exactly is a reference variable ??? - This should be clear now....
BankAccount Mary; String s; |
In CS170, you have learned that a reference variable is defined as follows:
BankAccount Mary; // Mary is a reference variable String s; // s is a reference variable |
What exactly is a reference variable ??? - This should be clear now....
BankAccount Mary; // Mary contains the address // of a BankAccount object String s; // s contains the address // of a String object |
What happens inside a Java program when it executes the following statements:
BankAccount Mary; // Mary is a reference variable Mary = new BankAccount( ); |
I will illustrates the effects of each statement with diagrams:
The variable definition will create (= reserve) 4 bytes memory to store an 32 bits address:
BankAccount Mary; // Mary is a reference variable
Mary = new BankAccount( );
|
The Java compiler will remember the address of the variable associated the identifier Mary:
The new BankAccount( ) expression will create (= reserve) a BankAccount object:
BankAccount Mary; // Mary is a reference variable
Mary = new BankAccount( );
|
The new BankAccount( ) expression returns the address of the new object:
The assignment operator will assign (= store) the return value in memory associated with Mary:
BankAccount Mary; // Mary is a reference variable
Mary = new BankAccount( );
|
Result: the reference variable Mary points to the new BankAccount object:
The value stored in the program counter (PC) is a program reference (= memory address):
The value stored in the program counter (PC) is a program reference (= memory address):
You can see that the PC is pointing at memory location 44 !!!