This is a discussion of the code we covered in class. I wanted to explain it in terms of the address of the variables, but I found this to be difficult in java. I could have explained it in C++, but there is no sense confusing you with unnecessary information.
I think part of the confusion in class was that we use the same variable name in the function. I have an annotated version of the program listed here, it should explain what is happening. I have links to the actual working code at the bottom of this page.
import java.io.*; /** *Example of reference call *Working code for this example Ref.java Point.java* This shows a (possibly) unexpected return from a function. *
*@author Kenneth L Moore *@version May 31, 2002 * */ public class Ref{ private final static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); private final static PrintWriter stdOut = new PrintWriter(System.out, true); private final static PrintWriter stdErr = new PrintWriter(System.err, true); private static void main(String[] args) throws IOException, NumberFormatException { int x = 5; // create an instance of a point initialized to 5,5 Point p = new Point(5, 5); // call the function f(p, x); // print out the state of the variables after the function call stdOut.println("p is (" + p.getX() + ", " +p.getY() + "), x is " + x); } private static void f(Point notTheSame_p, int notTheSame_x) { // here we have a variable (notTheSame_p) that contains a reference to p // since here notTheSame_p is referencing the instance created in main // we can change values of the instance created in main. notTheSame_p.setX(10); notTheSame_p.setY(10); // this is a copy of x and assigment is to a local variable notTheSame_x = 10; // within the scope of this function we change what the variable is referencing // this has NO effect on the variable p in main. notTheSame_p = new Point(20, 20); // the variables (notTheSame_p and notTheSame_x) go out of scope (existance) here // we now have nothing referencing the new instance of Point // the localy created Point(20,20) will be cleaned up by garbage collection. } }