Here is a program with two simple classes.
Person has two instance variables, a constructor that gives them values, and a
print method that shows their current values.
public class Person {
public int age;
public String name;
public Person(int a, String b) {
age = a;
name = b;
}
public void print() {
System.out.println(age + " " + name);
}
}
Given the following code in the class with the main method,
what will the program print when it runs, and why?
public class Test {
private static int i = 10;
public static void main(String[] args) {
String str = "I think, therefore I am. I think.";
Person p1 = new Person(21, "Lois");
Person p2 = new Person(20, "Clark");
mixUp(i, str, p1, p2);
System.out.println("i: " + i + " str: " + str);
p1.print();
p2.print();
}
private static void mixUp(int i, String str,
Person one, Person two) {
i++;
str = "First things first, " +
" but not necessarily in that order.";
one = two;
one.age = 34;
one.name = "Jimmy";
}
}
Answer:
i: 10 str: I think, therefore I am. I think. 21 Lois 34 Jimmy
The value of the instance variable i does not change because it is value of
the parameter i in the method mixUp() that is being incremented.
For the same reason, the value of the local variable str in main
does not change.
When mixUp, its parameters get the values that i and str have
within main where the call takes place.
The statement one = two; makes the pointer one (originally pointing to
where p1 points) point to the same place as two (that is, to where p2 points).
Then the age
and name of that object (now pointed to by one, two, and p2) are
modified. Thus, back in the main method, p1 remains the same
because it was never modified while the object pointed to by p2
is changed (though it is still the same object).