Java Reference
In-Depth Information
The sequence of execution of operators with equal precedence in a statement is determined by a property
called associativity . Each group of operators appearing on the same line in the table above are either
left associative or right associative . A left associative operator attaches to its immediate left
operand. This results in an expression involving several left associative operators with the same precedence
in the same expression being executed in sequence starting with the leftmost and ending with the rightmost.
Right associative operators of equal precedence in an expression bind to their right operand and
consequently are executed from right to left. For example, if you write the statement:
a = b + c + 10;
the left associativity of the group to which the + operator belongs implies that this is effectively:
a = (b + c) + 10;
On the other hand, = and op = are right associative, so if you have int variables a , b , c , and d each
initialized to 1, the statement:
a += b = c += d = 10;
sets a to 12, b and c to 11, and d to 10. The statement is equivalent to:
a += (b = (c += (d = 10)));
Note that these statements are intended to illustrate how associativity works, and are not a
recommended approach to coding.
You will probably find that you will learn the precedence and associativity of the operators in Java by
just using them in your programs. You may need to refer back to the table from time to time, but as you
gain experience you will gain a feel for where the operators sit and eventually you will automatically
know when you need parentheses and when not.
Program Comments
We have been adding comments in all our examples so far, so you already know that // plus everything
following in a line is ignored by the compiler (except when the // appears in a character string between
double quotes of course). Another use for // is to comment out lines of code. If you want to remove some
code from a program temporarily, you just need to add // at the beginning of each line you want to eliminate.
It is often convenient to include multiple lines of comment in a program, for example, at the beginning
of a method to explain what it does. An alternative to using // at the beginning of each line in a block of
comments is to put /* at the beginning of the first comment line and */ at the end of the last comment
line. Everything between the /* and the next */ will be ignored. By this means you can annotate your
programs, like this for example:
/***************************************
* This is a long explanation of *
* some particularly important *
* aspect of program operation. *
***************************************/
Search WWH ::




Custom Search