Java Reference
In-Depth Information
Multiplicative Operators
Java has three multiplicative operators: multiplication (*), division (/), and modulus (%). (The modulus
operator is often called mod or modulo; in Java shops, you hear expressions such as “a mod b” when
someone reads code aloud.)
As I mentioned earlier when discussing parentheses, there's no implicit order of operations between
these three operators. To the JVM, they all have the same precedence. Because that's the case, the JVM
processes them from left to right. Again, Java isn't algebra, though some of the operators and concepts
exist in both.
Multiplication and division are obvious enough, but let's look at the modulus operator. As ever,
examples help a lot (see Listing 4-7).
Listing 4-7. Modulus operator examples
int a = 9;
int b = 2;
int c = a % b; // c equals 1
float f = 1.9f;
float g = 0.4f;
float h = f % g; // h equals 0.3 - but beware of rounding
As this brief listing shows, the modulus operator divides the first operand by the second operand
and returns the remainder.
Caution Beware of rounding when using the modulus operator on floats and doubles. I rounded this to 0.3, but
my JVM actually assigned 0.29999995 to h when I ran this bit of code in Eclipse. That might not matter if you're
plotting the location of an avatar in a video game (because the screen has a fairly low number of pixels, so the
error isn't large enough to put the avatar in the wrong spot). However, imagine the same error in code that controls
a rocket going to Mars. Then it's a large enough error to ensure that your rocket doesn't end up in the right spot to
go into orbit, and that's an expensive error indeed. Rounding tends to be problematic in many applications.
Additive Operators
You might not think I'd have much to say about plus (+) and minus (-). However, even they have
subtleties worth noting when used in a Java application. As with the multiplicative operators, the order
of precedence for the additive operators is the same, so they get processed from left to right, even when
the minus precedes the plus operator on a line. That usually doesn't matter. However, when it does
matter, it can be a difficult problem to spot.
Also, the plus sign is the string concatenation operator. As we see in various examples, someString +
someOtherString = aThirdString . Strictly speaking, the addition operator and the string concatenation
operator are different operators. However, they use the same character. The JVM figures whether to use
a plus sign as the addition operator or as the string concatenation operator by context. If the JVM
determines that the context is numeric, it performs addition operations. If the JVM determines that the
Search WWH ::




Custom Search