Java Reference
In-Depth Information
Suppose that x , y , and z are int variables. The following is a legal statement in Java:
x = y = z;
2
In this statement, first the value of z is assigned to y , and then the new value of y is
assigned to x . Because the assignment operator = is evaluated from right to left, the
associativity of the assignment operator is said to be from right to left.
Earlier, you learned that if a variable is used in an expression, the expression yields a
meaningful value only if the variable has been initialized previously. You also learned that
after declaring a variable, you can use an assignment statement to initialize it. It is possible
to initialize and declare variables simultaneously. Before we discuss how to use an input
(read) statement, we address this important issue.
Declaring and Initializing Variables
When a variable is declared, Java might not automatically put a meaningful value into it.
In other words, Java might not automatically initialize all the variables you declare. For
example, the int and double variables might not be initialized to 0 , as happens in some
programming languages.
If you declare a variable and then use it in an expression without first initializing it, when
you compile the program you are likely to get an error. To avoid these pitfalls, Java allows
you to initialize variables while they are being declared. Consider the following Java
statements, in which variables are first declared and then initialized:
int first;
int second;
char ch;
double x;
double y;
first = 13;
second = 10;
ch = ' ';
x = 12.6;
y = 123.456;
You can declare and initialize these variables at the same time using the following Java
statements:
int first = 13;
int second = 10;
char ch = ' ';
double x = 12.6;
double y = 123.456;
The first Java statement declares the int variable first and stores 13 in it. The second
Java statement declares the int variable second and stores 10 in it. The other statements
have similar meanings. Declaring and initializing variables simultaneously is another way
to place meaningful data into a variable.
 
 
Search WWH ::




Custom Search