Java Reference
In-Depth Information
perimeter = PI * (2 * radius);
radius = 0;
// Fruitless effort!
return;
}
}
The method circleData() receives the radius of a circle as a parameter
and calculates its area and circumference. The calculated values are
stored in global variables; where they can be accessed by the caller.
Programmers note:
The method circleData() of the program Circle.java, is defined with
return type void. In this case the method returns nothing to the caller
since the information is contained in global variables.
Passing by Value and by Reference
Data is passed to methods in two different ways: by value and by reference .
Data is said to be passed by value when the method receives a copy of the
values in the caller's arguments. The result of passing by value is that the
method has no access to the variables where the data is stored. On the other
hand, when data is passed by reference, the method receives the addresses
of the variables where the values are stored. In this case, the method can
change the actual contents of the variables.
Java has simple rules that determine when data is passed by value or
by reference. Primitive data types are always passed by reference to
methods. In the program named Circle.java, listed previously, the method
circleData() receives the radius of the circle as a parameter from the
caller. The method attempts to change the value of this variable in the
statement:
radius = 0;
// Fruitless effort!
In the comment to this line we said that this is a “fruitless effort.” The
reason is that the method circleData() has no access to the variable ra-
dius, which is local to the method main(). The first println statement in
the caller's code shows that the value of the variable radius remains un-
changed.
Search WWH ::




Custom Search