1.寫出 第21、24行的執行結果。(畫出box-pointer指示圖會對答題很有幫助)
1 public class Shock {
2 public static int bang;
3 public static Shock baby;
4 public Shock() {
5 this.bang = 100;
6 }
7 public Shock (int num) {
8 this.bang = num;
9 baby = starter();
10 this.bang += num;
11 }
12 public static Shock starter() {
13 Shock gear = new Shock();
14 return gear;
15 }
16 public static void shrink(Shock statik) {
17 statik.bang -= 1;
18 }
19 public static void main(String[] args) {
20 Shock gear = new Shock(200);
21 System.out.println(gear.bang); __300______
22 shrink(gear);
23 shrink(starter());
24 System.out.println(gear.bang); __99______
25 }
26 }
- 為下列程式畫出box-ptr圖,並說明程式輸出是什麼
public class Horse {
Horse same;
String jimmy;
public Horse(String lee) {
jimmy = lee;
}
public Horse same(Horse horse) {
if (same != null) {
Horse same = horse;
same.same = horse;
same = horse.same;
}
return same.same;
}
public static void main(String[] args) {
Horse horse = new Horse("youve been");
Horse cult = new Horse("horsed");
cult.same = cult;
cult = cult.same(horse);
System.out.println(cult.jimmy);
System.out.println(horse.jimmy);
}
}
- 填寫main中 foobar 和baz 的 x、y的值,
1 public class Foo {
2 public int x, y;
3
4 public Foo (int x, int y) {
5 this.x = x;
6 this.y = y;
7 }
8
9 public static void switcheroo (Foo a, Foo b) {
10 Foo temp = a;
11 a = b;
12 b = temp;
13 }
14
15 public static void fliperoo (Foo a, Foo b) {
16 Foo temp = new Foo(a.x, a.y);
17 a.x = b.x;
18 a.y = b.y;
19 b.x = temp.x;
20 b.y = temp.y;
21 }
22
23 public static void swaperoo (Foo a, Foo b) {
24 Foo temp = a;
25 a.x = b.x;
26 a.y = b.y;
27 b.x = temp.x;
28 b.y = temp.y;
29 }
30
31 public static void main (String[] args) {
32 Foo foobar = new Foo(10, 20);
33 Foo baz = new Foo(30, 40);
34 switcheroo(foobar, baz); foobar.x: __10_ foobar.y: _20__ baz.x: __30_ baz.y: _40__
35 fliperoo(foobar, baz); foobar.x: _30__ foobar.y: _40__ baz.x: __10_ baz.y: _20__
36 swaperoo(foobar, baz); foobar.x: _10__ foobar.y: _20__ baz.x: _10__ baz.y: _20__
37 }
38 }
switcheroo 內部變完,不影響外部。
fliperoo 會影響外部,交換兩個Foo例項的值
swaperoo 會影響外部,把Foo a 的x、y 值變成Foo b的x、y值
- 下列程式執行後 ,arr的內容會是什麼?
public class QuikMaths {
public static void mulitplyBy3(int[] A) {
for (int x: A) {
x = x * 3;
}
}
public static void multiplyBy2(int[] A) {
int[] B = A;
for (int i = 0; i < B.length; i+= 1) {
B[i] *= 2;
}
}
public static void swap (int A, int B ) {
int temp = B;
B = A;
A = temp;
}
public static void main(String[] args) {
int[] arr;
arr = new int[]{2, 3, 3, 4};
multiplyBy3(arr);
/* Value of arr: {2, 3, 3, 4} */
arr = new int[]{2, 3, 3, 4};
multiplyBy2(arr);
/* Value of arr: {4, 6, 6, 8} */
int a = 6;
int b = 7;
swap(a, b);
/* Value of a: 6 Value of b: 7 */
}
}