ITI 1121. Introduction to Computing II – subtitle
public class TestSwapArrayInt {
public static void swap(int[] xs) {
int[] ys;
ys = new int[2];
ys[0] = xs[1];
ys[1] = xs[0];
xs = ys;
}
public static void main(String[] args) {
int[] xs;
xs = new int[2];
xs[0] = 15;
xs[1] = 21;
swap(xs);
System.out.println(xs[0]);
System.out.println(xs[1]);
}
}
args
xs
main
15 21
Working memory for the method main.
public class TestSwapArrayInt {
public static void swap(int[] xs) {
int[] ys;
ys = new int[2];
ys[0] = xs[1];
ys[1] = xs[0];
xs = ys;
}
public static void main(String[] args) {
int[] xs;
xs = new int[2];
xs[0] = 15;
xs[1] = 21;
swap(xs);
System.out.println(xs[0]);
System.out.println(xs[1]);
}
}
args
xs
main
15 21
xs
ys
swap
Calling the method swap. The value of the actual parameter is copied to the formal
parameter.
public class TestSwapArrayInt {
public static void swap(int[] xs) {
int[] ys;
ys = new int[2];
ys[0] = xs[1];
ys[1] = xs[0];
xs = ys;
}
public static void main(String[] args) {
int[] xs;
xs = new int[2];
xs[0] = 15;
xs[1] = 21;
swap(xs);
System.out.println(xs[0]);
System.out.println(xs[1]);
}
}
args
xs
main
15 21
xs
ys
swap
21 15
Creating an array and saving the reference into the variable ys. Copying xs[1] into ys[0]
and xs[0] into ys[1].
public class TestSwapArrayInt {
public static void swap(int[] xs) {
int[] ys;
ys = new int[2];
ys[0] = xs[1];
ys[1] = xs[0];
xs = ys;
}
public static void main(String[] args) {
int[] xs;
xs = new int[2];
xs[0] = 15;
xs[1] = 21;
swap(xs);
System.out.println(xs[0]);
System.out.println(xs[1]);
}
}
args
xs
main
15 21
xs
ys
swap
21 15
Copying the content of ys into xs (the formal parameter of the method swap).
public class TestSwapArrayInt {
public static void swap(int[] xs) {
int[] ys;
ys = new int[2];
ys[0] = xs[1];
ys[1] = xs[0];
xs = ys;
}
public static void main(String[] args) {
int[] xs;
xs = new int[2];
xs[0] = 15;
xs[1] = 21;
swap(xs);
System.out.println(xs[0]);
System.out.println(xs[1]);
}
}
args
xs
main
15 21
Returning to the method main. The working memory for swap is destroyed. Printing
xs[0] and xs[1] (the local variable xs for the method main).