Arithmetic Operators

     

These are +, *, -, and / for addition, multiplication, subtraction, and division. That's about it.

There is also the modulus operator, which looks like this: %. If you can't remember modulus , which actually comes in handy with surprising frequency, it is used to return the remainder of performing a division operation.

For example, 10 % 3 = 1, because 10 divided by 3 is 3 (which we don't care about) with a remainder of 1 (which is what we care about when we use modulus).

There's one more thing: you can use a special shorthand in combination with any of the arithmetic operators (excluding modulus) to modify an existing value.

Say you have a variable of type int called x and its value is 0, and you want to add 1 to it. You can do this the boring old nerdy way, like this:

 

 x = x + 1; //x is now whatever it was before (0 in this case), //plus 1 

Or you can do what all the cool kids do, and write it more concisely, like this:

 

 x += 1; //x is now whatever it was before (0 in this case), //plus 1 

With this incredible time-and space-saving feature, you can shave hundreds of minutes off of your programming time. (Maybe, I guess, if you programmed for billions and billions of years . And were a pretty slow typist.)

Although the way I have written it here is the most common way you see this feature used (with the addition operator adding 1 to the value), you could go crazy with it, using other operators:

 

 int x = 18; x /= 6; //x is 3 

The + operator is called an overloaded operator. That means it does something different in different contexts. We have seen how it works with integer values. It also can be used to concatenate (stick together) Strings. Like so:

 

 String s = "pound"; String t = "com" + s; //compound String x = "before "; x += t; //value of x is now "before compound" 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net