Java Reference
In-Depth Information
Suppose that there are two
int
variables,
num1
and
num2
. The following assignment,
num1 = num2
, assigns the
value
200
stored in
num2
to
num1
:
int num1 = 100; // num1 is 100
int num2 = 200; // num2 is 200
num1 = num2; // num1 is 200. num2 is 200
num2 = 500; // num2 is 500. num1 is still 200
When you say
num1 = num2
, the value stored in
num2
is copied to
num1
, and both
num1
and
num2
maintain their
own copy of the same value
200
. Later on, when
num2 = 500
is executed, the value of only
num2
changes to
500
. But
the value of
num1
remains the same:
200
. Now, suppose there are two reference variable,
ref1
and
ref2
, which refer to
two different objects of the same class. If you write
Object ref1 = new Object(); // An object
Object ref2 = new Object(); // An object
ref1 = ref2;
the effect of the expression
ref1 = ref2
is that both reference variables,
ref1
and
ref2
, now refer to the same object
in memory: the object that was being referred to by
ref2
. After this assignment, both reference variables,
ref1
and
ref2
, are equally capable of manipulating the object. The changes made to the object in memory by reference variable
ref1
will be observed by
ref2
also and vice versa. The chapter on classes and objects discusses more about reference
variable assignments.
Declaration, Initialization, and Assignment
Before a variable of any type is used in a Java program, it must be declared and must have a value assigned to it.
Suppose you want to use an
int
variable named
num1
. First, you must declare it.
int num1; // Declaration of a variable num1
A value can be assigned to a variable after it is declared or at the time of declaration itself. When a value is
assigned to a variable after it has been declared, it is known as assignment. The following piece of code declares an
int
variable
num2
and assigns 50 to it:
int num2; // Declaration of a variable num2
num2 = 50; // Assignment
When a value is assigned to a variable at the time of declaration itself, it is known as initialization. The following
code declares an
int
variable
num3
and initializes it to a value 100:
int num3 = 100; // Declaration of variable num3 and its initialization
You can declare more than one variable of the same type in one declaration by separating each variable name by
a comma.
// Declaration of three variables num1, num2 and num3 of type int
int num1, num2, num3;