class Rec { String name; int studentNum; float GPA; }How do these two Java statements compare?
b = a;below, it's important to think very carefully about what this means. Step through the code below to find out. If you'd like a challenge, try tracing it on paper yourself first.
Hint: When writing code with references, diagrams like these can really help you avoid bugs.
int x; int y; x = 22; y = x; y = 33;
The answer to the above question seems pretty obvious when we use integer variables, but we need to think more carefully when we do the same thing using two reference variables that refer to the same object.
Question D:
Now consider the following
code:
Node a; Node b; a = new Node(); a.key = 44; b = a; b.key = 55;What is the value of a.key and b.key after this code has been executed?
When two or more variables refer to the same object one is the alias of the other. In other words, we can refer to the same object using more than one name (reference).
Trace the following code to see what happens when we use aliases:
One way to think about this is to use an analogy of offices with blackboards in them. Suppose I tell you to go erase the blackboard in Room 7b and write your name on it. Then suppose I tell someone else to do the same. If you go back to room 7b afterwards, you will see their name, not yours. The office is like the object, and the room number is like the reference value -- it tells people where the office is.
You can avoid unwanted surprises and can save yourself many hours of debugging by drawing careful diagrams as you write and later trace your code.
In Java it is okay drop the last reference to an object that will not be used again. Java's garbage collector will eventually reclaim that lost memory. However, if we want to access that object again, we cannot.
Here is a challenge. For each of the following pieces of code, select the potential problem that appears in the code, or select Okay if the code has no problems.
Node a; Node b; b = new Node(); a = new Node(); a = b; a.key = 15;
Node a; Node b; b.key = 22; a = new Node(); a.key = 15;
Node b; Node a; b = new Node(); b.key = 10; a = b; a.key = 15;
Node b; Node a; b = new Node(); b.key = 75; a = b; a.key = 22; a = new Node(); a.key = 88;
Node a; Node b; a = new Node(); b = new Node(); b.key = 10; a.link = null;what two additional statements will lead to the following diagram?