Java Language Inside-Out

FAQ

  1. pass-by-value vs pass-by-reference
  2. what is dominator tree?

 

 

 

 

Solutions:

1

Pass-by-value Pass-by-reference
The actual parameter is fully evaluated and the resulting value is copied into a location(typically, on stack) The formal parameter merely acts as an alias for the acutal parameter
public void foo(Dog d) {
    d = new Dog("Fifi"); // creating the "Fifi" dog
}

Dog aDog = new Dog("Max"); // creating the "Max" dog
// at this point, aDog points to the "Max" dog
foo(aDog);
// aDog still points to the "Max" dog

declaration

//When you write that definition, you are defining a pointer to a Dog object, not a Dog object itself.
Dog d;

calling

//passes the value of d to foo; it does not pass the object that d points to!
foo(d);

 another example

1 Dog myDog = new Dog("Rover");
2 foo(myDog);
3 
4 public void foo(Dog someDog) {
5     someDog.setName("Max");   
6     someDog = new Dog("Fifi"); 
7     someDog.setName("Rowlf"); 
8 }

Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.

Let's look at what's happening.

the parameter someDog is set to the value 42.(fully evaluated.)

at line 5
someDog is followed to the Dog it points to (the Dog object at address 42) that Dog (the one at address 42) is asked to change his name to Max.
at line 6
a new Dog is created. Let's say he's at address 74 we assign the parameter someDog to 74.
at line 7
someDog is followed to the Dog it points to (the Dog object at address 74) that Dog (the one at address 74) is asked to change his name to Rowlf then, we return

Now let's think about what happens outside the method:

Did myDog change?

There's the key.

Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog.

 

2

Applying this to memory management, object A is dominator for object B when there is no object C which holds a reference to B. A dominator tree is a partial tree in which this condition holds true for all nodes from the root node. When the root reference is freed, the whole dominator tree is freed as well.

 

 

posted on 2012-07-13 21:17  grep  阅读(194)  评论(0编辑  收藏  举报