Java Reference
In-Depth Information
3
main
inc
i = 3
i = 4
FIGURE 4.2:
Passing parameters between methods.
inc( i ) ;
System.out.println(i);
}
}
If you guessed 4, you guessed incorrectly. Look at Figure 4.2. The
main
method declares
the variable
i
. This variable is local to the
main
method and is only defined inside the
main
method. When the
inc
method is called, the value of the variable and not the actual
variable is passed to the
inc
method. In other words, the
inc
method only gets as input
the number 3. Now, the
inc
method has a local variable of its own, which also happens to
be called
i
. This variable is modified from 3 to 4. After the method terminates, the variable
i
of the
inc
method is automatically deleted. This is done by the Java
garbage collector
.
The Java garbage collector looks at main memory that cannot be referenced and it frees it
so it can be allocated again. Next, control is passed back to the
main
method. The variable
i
inside the
main
method has not changed and it is still equal to 3.
In Java, variables of primitive type (e.g.,
int
,
double
,
char
, etc.) are passed by
value when methods are called. This means that any modification to the variables of
the method will not be seen by the calling method.
Next, suppose that we want to rewrite the program in a way that allows us to change
the value of
i
. We have two options. First, the new value of
i
can be sent back as a return
value of the method. The rewritten code follows.
import
java . util .
∗
;
public class
Example
{
public static int
inc(
int
i)
{
i ++;
return
i;
}
public static void
main(String [] args)
{
int
i=3;
i=inc(i);
System.out.println(i);
}
}
Now, the
inc
method sends back the new value of the variable
i
in the
inc
method
(i.e., the value 4). The assignment operator changes the variable
i
in the
main
method to
4. Alternatively, the variable
i
can be defined as a global variable as shown next.
import
java . util .
∗
;
public class
Example
{
static int
i;
public static void
inc()
{