Java Reference
In-Depth Information
Pass-by-value (here
the value is 5)
Stack
Heap
Space required for the
printArea method
int times: 5
Circle c:
Pass-by-value
(here the value is
the reference for
the object)
reference
Space required for the
main method
int n: 5
myCircle:
A Circle
object
reference
F IGURE 8.18 The value of n is passed to times , and the reference to myCircle is passed to
c in the printAreas method.
8.23
Describe the difference between passing a parameter of a primitive type and passing
a parameter of a reference type. Show the output of the following programs:
Check
Point
public class Test {
public static void main(String[] args) {
Count myCount = new Count();
int times = 0 ;
public class Count {
public int count;
public Count( int c) {
count = c;
for ( int i = 0 ; i < 100 ; i++)
increment(myCount, times);
}
public Count() {
count = 1 ;
System.out.println( "count is " + myCount.count);
System.out.println( "times is " + times);
}
}
}
public static void increment(Count c, int times) {
c.count++;
times++;
}
}
8.24
Show the output of the following program:
public class Test {
public static void main(String[] args) {
Circle circle1 = new Circle( 1 );
Circle circle2 = new Circle( 2 );
swap1(circle1, circle2);
System.out.println( "After swap1: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);
swap2(circle1, circle2);
System.out.println( "After swap2: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);
}
public static void swap1(Circle x, Circle y) {
Circle temp = x;
x = y;
y = temp;
 
Search WWH ::




Custom Search