File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Arguments" Watch "Arguments" New topic
Author

Arguments

May-Yoong Cheah
Greenhorn

Joined: Apr 02, 2003
Posts: 8
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

Joined: Aug 02, 2004
Posts: 161
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.


Co-Author of <a href="http://www.oreilly.com/catalog/jswing2" target="_blank" rel="nofollow">Java Swing</a><br />Co-Creator of <a href="http://www.sun.com/training/catalog/courses/CX-310-055.xml" target="_blank" rel="nofollow">SCJP 5.0</a> and <a href="http://www.sun.com/training/certification/java/associate_beta.xml" target="_blank" rel="nofollow">SCJA</a> exams
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arguments
 
Similar Threads
argument question
passing array in to method...doubt
Method Arguments
Dan's Exam Array Doubt
Passing an Array Reference