Java Reference
In-Depth Information
id
131072
785
Variable name
Value stored at the address
Memory address
Figure 6-4. Relationship between a variable name, its memory address, and data
In Figure 6-4 , you see that the actual data of the variable id is stored at the memory address. You can also store a
data at a memory address, which is not the actual value for the variable; rather it is the memory address of the location
where the actual value is stored. In this case, the value stored at the first memory address is a reference to the actual
data stored at some other memory address, and such a value is known as a reference or a pointer. If a variable stores
the reference to some data, it is called a reference variable.
Contrast the phrases “a variable” and “a reference variable.” A variable stores the actual data itself at its memory
location. A reference variable stores the reference (or memory address) of the actual data. Figure 6-5 depicts the
difference between a variable and a reference variable. Here, idRef is a reference variable and id is a variable. Both
variables are allocated memory separately. The actual value of 785 is stored at the memory location of id variable,
which is 131072 . However, the memory location ( 262144 ) of idRef stores the address of the id variable (or address or
memory location, where 785 is stored). You can get to the value 785 in memory using either variable. The operation to
get the actual data that a reference variable refers to is called dereferencing.
131072
id
785
262144
idRef
131072
Figure 6-5. Difference between a variable and a reference variable
A method (also called function or procedure in some programming languages) can optionally accept parameters
from its caller. A method's parameters allow data sharing between the caller context and the method context.
Many mechanisms are in practice to pass the parameters to a method. The following sections discuss some of the
commonly used parameter passing mechanisms.
Pass By Value
Pass by value is the simplest parameter passing mechanism to understand. However, it is not necessarily the most
efficient and the easiest to implement in all situations. When a method is called, the values of the actual parameters
are copied to the formal parameters. When the method execution starts, two copies of the value exist in memory:
one copy for the actual parameter and one copy for the formal parameter. Inside the method, the formal parameter
operates on its own copy of the value. Any changes made to the value of the formal parameter do not affect the value
of the actual parameter.
 
Search WWH ::




Custom Search