Next: Comparisons. Up: Expressions and loops. Previous: None.
Textbook: Section 2.7
You can build up expressions in Java using operators. For now, we'll look at just five operators:
+ | addition |
- | subtraction |
/ | division |
* | multiplication |
% | remainder / modulus |
You can use these in your assignment statements. Consider, for example, the following segment of code.
When the computer runs the second line, it computesint i = 5; int j = 2 * i + 1; IO.println(j);
2*i+1
. Since i
holds 5 at this point, this
computation yields the number 2*5+1=11. Thus 5 goes into the memory that
j
refers to. And then the next line prints the value of
j
, so it displays 11.
Java observes the order of operations. Thus, 1+2*i
means
to multiply 2 by i
first, and then add 1 to it. Of course
you can override this using parentheses.
When an operator has an integer expression on either side of it, it computes an integer. This means that when you divide two integers, you get an integer back!
So what's 1/2
? The computer will perform the division
and ignore any remainder. In this case, the division yields 0 with a
remainder of 1, so 1/2
evaluates to the integer 0! You're
bound to run into problems with this if you're not careful.
If either side of the operator is a double,
the computer will compute a double result. So
1.0/2
gives the double value 0.5.
Java supports two unary operators.
+ | positive |
- | negative |
In this example, we've used the binary `-' operator to subtract 1 fromj = -(i - 1);
i
, and we've used the unary
`-' operator to negate the result.
Java distinguishes between the two based on context.
(If i held the number
5, then this statement would put the number -4 into j.)
The unary + operator is useless. Java includes it for completeness only.
Java provides some additional combination operators for convenience.
+= | add and assign |
-= | subtract and assign |
/= | divide and assign |
*= | multiply and assign |
%= | modulo and assign |
Say i held 5 and j held 11. The computer would add i and 1, giving 6; it would multiply 11 by this, giving 66; and it would put this 66 back into j.j *= i + 1;
All the assignment operators rank below the arithmetic operators we already saw in the precedence hierarchy. So it's multiplication/division/modulus, followed by addition/subtraction, followed by the various assignment operators.
Next: Comparisons. Up: Expressions and loops. Previous: None.