Java Reference
In-Depth Information
both changes the value of number to 3 and evaluates to the value 3 . This allows you to
chain assignment statements. The following changes the values of both the variables,
number1 and number2 , to 3 :
number2 = (number1 = 3);
The assignment operator automatically is executed right-to-left if there are no paren-
theses, so this is normally written in the following equivalent way:
number2 = number1 = 3;
TIP: Initialize Variables
A variable that has been declared but that has not yet been given a value by some
means, such as an assignment statement, is said to be uninitialized . In some cases an
uninitialized variable may be given some default value, but this is not true in all
cases. Moreover, it makes your program clearer to explicitly give the variable a value,
even if you are simply reassigning it the default value. (The exact details on default
values have been known to change and should not be counted on.) 3
One easy way to ensure that you do not have an uninitialized variable is to initial-
ize it within the declaration. Simply combine the declaration and an assignment
statement, as in the following examples:
uninitialized
variable
int count = 0;
double speed = 65.5;
char grade = 'A';
int initialCount = 50, finalCount;
Note that you can initialize some variables and not initialize other variables in a
declaration.
Sometimes the compiler may say that you have failed to initialize a variable. In
most cases, you will indeed have failed to initialize the variable. Occasionally, the
compiler is mistaken in giving this advice. However, the compiler will not compile
your program until you convince it that the variable in question is initialized. To
make the compiler happy, initialize the variable when it is declared, even if the vari-
able will be given a different value before the variable is used for anything. In such
cases, you cannot argue with the compiler.
3
3 The official rules are that the variables we are now using, which we will later call local variables , are
not automatically initialized. Later in this topic we will introduce variables called static variables
and instance variables that are automatically initialized. However, we urge you to never rely on
automatic initialization.
Search WWH ::




Custom Search