[关闭]
@w1024020103 2017-02-05T22:00:23.000000Z 字数 1022 阅读 726

Test Your Understanding of the GRoE

cs61b


Exercise 2.1.1: Suppose we have the code below:

  1. public class PassByValueFigure {
  2. public static void main(String[] args) {
  3. Walrus walrus = new Walrus(3500, 10.5);
  4. int x = 9;
  5. doStuff(walrus, x);
  6. System.out.println(walrus);
  7. System.out.println(x);
  8. }
  9. public static void doStuff(Walrus W, int x) {
  10. W.weight = W.weight - 100;
  11. x = x - 5;
  12. }
  13. }

Does the call to doStuff have an effect on walrus and/or x? Hint: We only need to know the GRoE to solve this problem.

Answer: 3400,10.5 9

9.JPG-61.5kB

Visualizer

I thought if there's a return value of doStuff that is int type, x would change. let's try.
image_1b86tn27mdi21ktcka3to61nnf9.png-58.8kB
But still i got x = 9!!

I didn't get the point thoroughly i guess.
My understanding is that according to the visualizer shows,doStuff method and main method take different place in the memory. As for reference variables like walrus in two method, they actually point to the same object new Walrus, so they are the same thing. However, as far as the primitive type int x is considered, things are different. Because int x only take one place which is different for these two method in memory, and they don't point to object never mention the same object. That's why the two X s are not the same thing.

passing the parameter

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注