Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arguments

 
May-Yoong Cheah
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused about these two questions. They are the same except for the codes inside method m1 in class GFC304 and GFC305. I would like to know why values in array of i1 and i2 in class GFC304 remain unchanged while values in array of i1 and i2 in class GFC305 are changed.

Question 1
class GFC304 {
static void m1(int[] i1, int[] i2) {
int[] i3 = i1; i1 = i2; i2 = i3;
}
public static void main (String[] args) {
int[] i1 = {1}, i2 = {3}; m1(i1, i2);
System.out.print(i1[0] + "," + i2[0]);
}}

What is the result of attempting to compile and run the program?

a. Prints: 1,1
b. Prints: 1,3
c. Prints: 3,1
d. Prints: 3,3
e. Run-time error
f. Compile-time error
g. None of the above

Answer is b.

Question 2
class GFC305 {
static void m1(int[] i1, int[] i2) {
int i = i1[0]; i1[0] = i2[0]; i2[0] = i;
}
public static void main (String[] args) {
int[] i1 = {1}, i2 = {3}; m1(i1, i2);
System.out.print(i1[0] + "," + i2[0]);
}}

What is the result of attempting to compile and run the program?

a. Prints: 1,1
b. Prints: 1,3
c. Prints: 3,1
d. Prints: 3,3
e. Run-time error
f. Compile-time error
g. None of the above

Answer is c.
 
Dave Wood
bronco
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first question, the method is modifying local object references. Remember, an array is just a special type of object. Changing the local references doesn't impact the object that was passed in.

In the 2nd question, the method is changing the data WITHIN the array that is passed in.

Think of this just question just like you would:

vs.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic