Java Reference
In-Depth Information
Call-by-Value
When an argument is passed in to a parameter, the argument's data is copied
into the parameter. The process of copying data between method calls is
referred to in programming as call-by-value .
In Java, you do not specify that an argument is to be passed using call-
by-value. It happens automatically, and is, in fact, your only option. Other
programming languages use call-by-reference and/or call-by-pointer, in
which an argument is not copied into a parameter. You cannot do call-by-
reference or call-by-pointer in Java. No matter what type of argument you
pass in to a method, the corresponding parameter will get a copy of that
data, which is exactly how call-by-value works.
For example, to invoke the setVolume() method of the Radio class, you must
pass in an int argument:
int x = 7;
someRadio.setVolume(x);
In the previous statements, the integer x is passed in to setVolume(). The
contents of x are copied into the int parameter of setVolume(), which is the
variable volume. There are now two 7s in memory. The value of volume is 7,
and the value of x is still 7.
The following ListenToRadio program demonstrates passing arguments to
parameters. Try to determine the flow of control of the program and also what
the output will be.
public class ListenToRadio
{
public static void main(String [] args)
{
System.out.println(“Creating a radio...”);
Radio radio = new Radio();
System.out.println(“...and turning it on...”);
float initialStation = Float.parseFloat(args[0]);
int initialVolume = 5;
radio.turnOn(initialVolume, initialStation, 'F');
System.out.println(“The tuning is “ + radio.getTuning());
int x = 7;
radio.setVolume(x);
System.out.println(“x = “ + x);
radio.turnUp();
radio.turnUp();
radio.changeBand();
Search WWH ::




Custom Search