Java Reference
In-Depth Information
These conventions for managing numbers are easy to remember if you observe
this logic:
For integer math, the default type is int .
For floating-point math, the default type is double .
Smaller types can automatically be converted into larger types.
Larger types must be cast into smaller types. There is the possibility of data loss.
The size order is double , float , int , short , byte .
Java coders often use a shortcut (assignment with operator) to perform simple
math operations on a single variable:
x = x + 7;
x += 7; // the same statement
This coding style can take a little getting used to, since one of the source operands
(the second x) that would be expected in an algebraic expression is missing. The ad-
dition operator (+, in the example) is normally placed to the left of the = sign in this
type of complex assignment expression. Each of the math operators (*, /, +, and -)
can be combined with an assignment expression (e.g., *=, /=, +=, and -=).
Like C and C++, Java provides for increment and decrement operators ( ++ and
-- ). These provide a convenient mechanism to increment or decrement a variable.
x = 7;
x++; // x = 8
x--; // x = 7
These operators come in two types: the postfix (x++) and the prefix (++x). The
difference shows up when the auto increment operators are used in an expression.
The prefix operator increments or decrements before presenting the value, and the
postfix increments or decrements after presenting the value.
x = 7;
y = 2 * x++; // y = 14, and x = 8
x = 7;
y = 2 * ++x; // y = 16, and x = 8
As you can see from the examples, there are subtle differences between postfix
and prefix increment operators, especially when used as part of an expression. A
number of Java language authorities recommend that these operators not be used
as part of an expression, but only as standalone statements in order to avoid con-
fusion on this matter.
Search WWH ::




Custom Search