Java Reference
In-Depth Information
What value will myVar contain? Well, because the ++ is postfixed (it's after the myNumber variable),
it will be incremented afterward. So the equation reads: Multiply myNumber by 10 plus 1 and then
increment myNumber by one.
myVar = 1 * 10 + 1 = 11
Then add 1 to myNumber to get 12, but do this after the value 11 has been assigned to myVar . Now
take a look at the following code:
myNumber = 1;
myVar = ++ myNumber * 10 + 1;
This time myNumber is incremented by one first, then times 10 and plus 1:
myVar = 2 * 10 + 1 = 21
As you can imagine, such subtlety can easily be overlooked and lead to bugs in code; therefore, it's
usually best to avoid this syntax.
Before going on, this seems to be a good place to introduce another operator: +=. You can
use this operator as a shortcut for increasing the value held by a variable by a set amount. For
example,
myVar += 6;
does exactly the same thing as:
myVar = myVar + 6;
You can also do the same thing for subtraction and multiplication, as shown here:
myVar −= 6;
myVar * = 6;
which is equivalent to:
myVar = myVar - 6;
myVar = myVar * 6;
operator precedence
You've seen that symbols that perform some function—like +, which adds two numbers, and ,
which subtracts one number from another—are called operators. Unlike people, not all operators
are created equal; some have a higher precedence —that is, they get dealt with sooner. A quick look
at a simple example will help demonstrate this point:
var myVariable;
myVariable = 1 + 1 * 2;
alert(myVariable);
 
Search WWH ::




Custom Search