Java Reference
In-Depth Information
Manipulating Numeric Primitives
The standard mathematical operators are used to manipulate primitive variables. Table 5-2 shows the mathematical
symbols and examples.
Table 5-2.
Operation
Symbol
Example
Example result
Multiplication
*
3*2
6
Division
/
3/2
3.0/2.0
1
1.5
Addition
+
3+2
5
Subtraction
-
3-2
1
What is going on with that first division example? No, it is not a typo. If two integers are divided, any fractional
remainder is truncated (i.e., discarded). Notice that if floating point numbers (e.g., 3.0, 2.0) are specified, the fractional
result is retained. Looks like a source of many future errors. The Java developers have not done anything nice here!
In addition to the standard math operations, there is a Math class that has many “higher level” mathematical
functions (with a heavy emphasis on trigonometric functions such as sine, cosine, tangent, etc.). The Math class
methods can be “called directly.” “Called directly” means that you do not have to create a Math object to use the Math
class methods. This is because the Math class methods have been defined as static . You may remember the keyword
static from the main method definition. Just as the main method can be “called directly” (i.e., no object needs to be
created), any static method can be called by simply specifying the class and method name. Of course, each method
has a unique signature (meaning each method expects one or more specific variable types) and will return a specific
variable type. Table 5-3 contains some of the more common Math class methods and examples.
Table 5-3.
Operation
Expects
Returns
Examples
Example result
Exponent
2 numbers
double
Math.pow(3.0, 2);
9.0
Random
Nothing
double (value between 0 and 1)
Math.random();
Math.random();
0.6051898089070796
0.021619841296942277
Square Root
Number
double
Math.sqrt(3);
Math.sqrt(4.0);
1.7320508075688772
2.0
Two other math operations that you should be aware of are increment (++) and decrement (--). Increment and
decrement are specified with numeric primitive variables (e.g., intTest++; or --doubleTest; ) and will increase
or decrease a numeric primitive by 1. You cannot specify a different value, like 3, to increment or decrement by.
For instance, assuming intTest has a value of 2, intTest++; would result in a value of 3. If intTest has a value of 2,
intTest--; would result in a value of 1.
The increment and decrement operations could also be done with formulas such as intTest = intTest + 1 and
intTest = intTest - 1. So, essentially, increment and decrement simply offer a shorthand method for coding these
formulas. Now this may not sound like a big deal, but incrementing by one is used extensively when using loops. We
will explore looping in a later chapter and you will come to appreciate this shortcut more.
 
 
Search WWH ::




Custom Search