Java Reference
In-Depth Information
Continued from previous page
and out of your room. You have to check in first to get your room key, but then
you can come and go as often as you like. If you tried to check in a second time,
the hotel would be likely to ask you if you really want to pay for a second room.
If you declare a variable more than once, Java generates a compiler error. For
example, say your program contains the following lines:
int x = 13;
System.out.println(x);
int x = 2; // this line does not compile
System.out.println(x);
The first line is okay. It declares an integer variable called x and initializes it
to 13 . The second line is also okay, because it simply prints the value of x . But
the third line will generate an error message indicating that “ x is already
defined.” If you want to change the value of x you need to use a simple assign-
ment statement instead of a variable declaration:
int x = 13;
System.out.println(x);
x = 2;
System.out.println(x);
We have been referring to the “assignment statement,” but in fact assignment is an
operator, not a statement. When you assign a value to a variable, the overall expres-
sion evaluates to the value just assigned. That means that you can form expressions
that have assignment operators embedded within them. Unlike most other operators,
the assignment operator evaluates from right to left, which allows programmers to
write statements like the following:
int x, y, z;
x = y = z = 2 * 5 + 4;
Because the assignment operator evaluates from right to left, this statement is
equivalent to:
x = (y = (z = 2 * 5 + 4));
The expression 2 * 5 + 4 evaluates to 14 . This value is assigned to z . The
assignment is itself an expression that evaluates to 14 , which is then assigned to y .
The assignment to y evaluates to 14 as well, which is then assigned to x . The result is
that all three variables are assigned the value 14 .
 
Search WWH ::




Custom Search