SHORTCUT NOTATIONS
There are several ways to express a given computation; we seek clear, elegant, and efficient code. Such code often takes advantage of the following widely used shortcuts (that are found in many languages, not just Java).
Initializing declarations.
We can combine a declaration with an assignment to initialize a variable at the same time that it is declared (created). For example, the code int i = 1; creates an int variable named i and assigns it the initial value 1. A best practice is to use this mechanism close to first use of the variable (to limit scope).
Implicit assignments.
The following shortcuts are available when our purpose is to modify a variable’s value relative to its current value:
- Increment/decrement operators: i++ is the same as i = i + 1 and has the value i in an expression. Similarly, i-- is the same as i = i - 1. The code ++i and --i are the same except that the expression value is taken after the increment/decrement, not before.
- Other compound operations: Prepending a binary operator to the = in an assignment is equivalent to using the variable on the left as the first operand. For example, the code i/=2; is equivalent to the code i = i/2; Note that i += 1; has the same effect as i = i+1; (and i++).
Single-statement blocks.
If a block of statements in a conditional or a loop has only a single statement, the curly braces may be omitted.
For notation.
Many loops follow this scheme: initialize an index variable to some value and then use a while loop to test a loop continuation condition involving the index variable, where the last statement in the while loop increments the index variable. You can express such loops compactly with Java’s for notation:
for (<initialize>; <boolean expression>; <increment>) { <block statements> }
This code is, with only a few exceptions, equivalent to
<initialize>; while (<boolean expression>) { <block statements> <increment>; }
We use for loops to support this initialize-and-increment programming idiom.
statement |
examples |
definition |
declaration |
int i; double c; |
create a variable of a specified type, named with a given identifier |
assignment |
a = b + 3; discriminant = b*b - 4.0*c; |
assign a data-type value to a variable |
initializing |
int i = 1; double c = 3.141592625; |
declaration that also assigns an initial value |
implicit |
i++; i += 1; |
i = i + 1; |
conditional (if) |
if (x < 0) x = -x; |
execute a statement, |
conditional |
if (x > y) max = x; |
execute one or the other statement, |
loop (while) |
int v = 0; double t = c; |
execute statement |
loop (for) |
for (int i = 1; i <= N; i++) for (int i = 0; i <= N; i++)> |
compact version of while statement |
call |
int key = StdIn.readInt(); |
invoke other methods (see page 22) |
return |
return false; |
return from a method (see page 24) |
Java statements