Java Math Operators
Total Page:16
File Type:pdf, Size:1020Kb
Java Math Operators
The basic Java math operators are:
Math Operator Description
+ Performs addition - Performs subtraction * Performs multiplication / Performs division
Each of these math operators will be explained in more detail in the following sections.
Addition
The + operator performs an addition of two values. This can be an addition of two constants, a constant and a variable, or a variable and a variable. Here are a few Java addition examples: int sum1 = 10 + 20; // adding two constant values int sum2 = sum1 + 33; // adding a variable and a constant int sum3 = sum2 + sum2; // adding two variables
The + operator will replace the two values with the sum of the two values at runtime. So at the place where the expression sum1 + 33 is written, at runtime this will be replaced with the sum of the value of sum1 and the constant value 33. You can of course create longer chains of additions and thus add more than two numbers. Here is a an example of adding 3 or more values together: int sum1 = 10 + 20 + 30; int sum3 = sum2 + 99 + 123 + 1191;
A commonly used math operation on variables is to set the variable equal to its own value plus another value. Here is how that looks: int result = 10; result = result + 20;
The second line of this example sets the result variable equals to its own value (before being assigned the new value) + 20. Which means 10 + 20.
Since adding a value to a variable is a very common operation, Java contains a built-in operator for that specific purpose. It is the += operator. Here is the example above rewritten to use the += operator: int result = 10; result += 20;
The second line in this example adds 20 to the variable result. This equivalent to the code result = result + 20;
Subtraction The - operator performs subtraction of one value from another. This can be a subtraction of a constant value from another constant value, a constant value from a variable, or a variable from a variable. Here are a few Java subtraction examples: int diff1 = 200 - 10; int diff2 = diff1 - 5; int diff3 = diff1 - diff2;
The - operator will replace the two values with the difference between the two values, just like with the + operator.
You can create longer chains of subtractions and thus subtract more values from each other. Here is an example of sub- tracting two values from another in a single Java statement: int diff = 200 - 10 - 20;
This works for variables too.
Remember, minus minus equals plus, just like in normal math. Here is an example of that: int diff = 200 - (-10);
After executing this math expression the diff variable will contain the value 210 because - (-10) is equal to +10 ac- cording to standard math rules.
Just like with addition, Java contains an operator specifically targeted at subtracting a value from a variable, and assigning the result to the variable. Here is first how that would look in Java without this operator: int result = 200; result = result - 10;
Here is how the same math operation looks with the -= operator: int result = 200; result -= 10;
Multiplication
The * operator performs multiplication of two values. The values can be either two constant values, a variable and a con- stant value, or two variables. Here are a few Java multiplication examples: int prod1 = 10 * 20; int prod2 = prod1 * 5; int prod3 = prod1 * prod2;
The * operator will replace the multiplication math expression with the product of the two values at runtime. You can create longer chains of multiplication using the * operator. Here is an example of multiplying 3 values with each other: int prod = 10 * 20 * 30;
Multiplying a variable with a value and assigning the value back to the variable is a common math operation in Java appli- cations. Therefore Java contains an explicit operator for this operation. The *= operator. Here is first how the calculation would look without the *= operator: int result = 10; result = result * 20;
The second line of this example multiplies the value of the result variable (before being assigned the result of this cal- culation) with 20 and assigns the value back to the result variable. Here is how the same math operation looks with the *= operator: int result = 10; result *= 20;
Division
The / operator performs division of one value by another. This can be dividing one constant with another, dividing a vari- able with a constant, or dividing one variable by another variable. Here are a few Java division examples: int division1 = 100 / 10; int division2 = division1 / 2; int division3 = division1 / division2;
You can chain multiple values for division, but because of the Java math operator precedence (explained later) you have to pay attention to how you chain the values. Look at this division example: int division = 100 / 10 / 2;
After executing this math expression the division variable will contain the value 5. That is the result because the math expression was calculated by first dividing 100 by 10 (= 10) and then 10 by 2 (=5). But, what if you had wanted to first di- vide the 10 by 2 (=5), and then divide the 100 by 5 (=20) ? You would have had to use parentheses to achieve that, like this: int division = 100 / (10 / 2)
You will learn more about operator precedence and parentheses later in this Java math tutorial. Java also contains a shortcut operator for dividing the value of a variable by another value, and assigning that value back to the variable. The /= operator. Here is first how that math operation looks in Java without the /= operator: int result = 100; result = result / 5;
The second line of this example divides the value of the result variable (the value it had before being assigned the re- sult of this calculation) by 5, and assigns the result back to the result variable. Here is how the same math operation looks with the /= operator: int result = 100; result /= 5;
Remainder / Modulo
The remainder math operation performs an integer division of one value by another and returns the remained of that divi- sion. The remainder operation is also called the modulo operation. The operator for the remainder / modulo operation is the % (percentage) character. Here is a module operation example: int value = 100; int remainder = value % 9;
100 divided by 9 is 11 with a remainder of 1 (11 times 9 is 99). Thus, the remainder variable is assigned the value 1. Java also contains a shortcut operator for dividing a variable by another value and assigning the remainder of that division to the variable. The %= operator. Here is an example: int result = 100; result %= 9;
The second line of this example will assign the value 1 to the result variable. 1 is the result of 100 % 9.
Java Integer Math
Math operations performed on Java integer types (byte, short, int and long) behaves slightly different from how normal math operations work. Since Java integer types cannot contain fractions, each calculation involving one or more integer types have all fractions in the result cut off. Look at this math expression: int result = 100 / 8;
The result of this division would be 12.5 , but since the two numbers are integers, the .5 fraction is cut off. The result is therefore just 12. The rounding also occurs in subresults of larger calculations, as you will learn in the next section about Java floating point math.
Java Floating Point Math
Java contains the two floating point data types float and double. These floating point types are capable of containing fractions in the numbers. If you need fractions in your math expressions you should use one of these data types. Here is a Java floating point math expression example: double result = 100 / 8;
Even though the result variable is now a floating point type (double), the final result is still just 12 instead of 12.5 . The reason for that is that the two values in the math expression (100 and 8) are both integers. Thus, the result of dividing one by the other is first converted to an integer (12) before being assigned to the result variable.
To avoid rounding of calculations in math expressions in Java you must make sure that all data types involved in the math expression are floating point types. For instance, you could first assign the values to floating point variables like this: double no1 = 100; double no2 = 8; double result = no1 / no2;
Now the result variable would end up with the value 12.5. Java Math Operator Precedence
Once you start combining the Java math operators in math expressions it becomes important to control what calculations are to be executed when, in order to get the desired result. The Java math operators have a natural operator precedence which is similar to the precedence of standard math operators.
The math operators * and / for multiplication and division takes precedence over the + and - operators. That means, that multiplications and divisions are evaluated before addition and subtraction in math expressions. In case there are multiple * and / operators they will be calculated from left to right. Look at this Java math expression: int result = 100 * 100 / 5 + 200 * 3 / 2;
First the multiplications and divisions are executed. There are two groups of three multiplications and divisions. Each group is executed from left to right:
100 * 100 = 10000; 10000 / 5 = 2000; 200 * 3 = 600; 600 / 2 = 300;
After calculating the multiplications and divisions the math expression looks like this: int result = 2000 + 600;
Now the additions and subtractions are executed. The value assigned to the result variable is thus 2000 + 600 = 2600 .
You can control the operator precedence and sequence of calculations in math expressions in Java using parentheses. Math expressions inside parentheses have higher precedence than any other operator. Therefore expressions inside parentheses are calculated first. Inside parentheses the normal operator precedence applies. Here is the math expression from earlier, but with parentheses inserted which change the calculation: int result = 100 * 100 / (5 + 200) * 3 / 2;
The value 100 is still multiplied by 100 (= 10,000), but now it is divided by 5 + 200 (=205) instead of 5. After this divi- sion the result is multiplied by 3 and then divided by 2. The result of executing this math expression in Java is 72 (round- ing of calculations affect the result).
Basic Math Functions
The java.lang.Math contains a set of basic math functions for obtaining the absolute value, highest and lowest of two values, rounding of values, random values etc. These basic math functions of the Java Math class will be covered in the following sections.
Math.abs() The Math.abs() function returns the absolute value of the parameter passed to it. The absolute value is the positive val- ue of the parameter. If the parameter value is negative, the negative sign is removed and the positive value corresponding to the negative value without sign is returned. Here are two Math.abs() method examples: int abs1 = Math.abs(10); // abs1 = 10 int abs2 = Math.abs(-20); // abs2 = 20
The absolute value of 10 is 10. The absolute value of -20 is 20. The Math.abs() method is overloaded in 4 versions: Math.abs(int) Math.abs(long) Math.abs(float) Math.abs(double)
Which of these methods are called depends on the data type of the parameter passed to the Math.abs() method. You don’t need to worry too much about this issue for the AP exam, as long as you know how to use the method.
Math.pow()
The Math.pow() function takes two parameters. The method returns the value of the first parameter raised to the power of the second parameter. Here is a Math.pow() Java example: double pow2 = Math.pow(2,2); System.out.println("pow2 = " + pow2); double pow8 = Math.pow(2,8); System.out.println("pow8 = " + pow8);
The output from this Math.pow() example would be: pow2 = 4.0 pow8 = 256.0
In other words, the Math.pow() example calculate the values of 22 and 28 which are 4 and 256.
Math.sqrt()
The Math.sqrt() method calculates the square root of the parameter given to it. Here are a few Java Math.sqrt() example: double sqrt4 = Math.sqrt(4); System.out.println("sqrt4 = " + sqrt4); double sqrt9 = Math.sqrt(9); System.out.println("sqrt9 = " + sqrt9); The output printed from these Java Math.sqrt() examples would be: sqrt4 = 2.0 sqrt9 = 3.0 Math.min()
The Math.min() method returns the smallest of two values passed to it as parameter. Here is a Math.min() Java ex- ample: int min = Math.min(10, 20);
After executing this code the min variable will contain the value 10.
Math.max()
The Math.max() method returns the largest of two values passed to it as parameter. Here is a Math.max() Java ex- ample: int max = Math.max(10, 20);
After executing this code the max variable will contain the value 20.
Math.round()
The Math.round() method rounds a float or double to the nearest integer using normal math round rules (either up or down). Here is a Java Math.round() example: double roundedDown = Math.round(23.445); double roundedUp = Math.round(23.545);
After executing these two Java statements the roundedDown variable will contain the value 23.0 , and the round- edUp variable will contain the value 24.0.
Math.random()
The Math.random() method returns a random floating point number between 0 and 1. Of course the number is not ful- ly random, but the result of some calculation which is supposed to make it as unpredictable as possible. Here is a Java Math.random() example: double random = Math.random();
Math.PI The Math.PI constant is a double with a value that is very close to the value of PI - the mathematical definition of PI. You will often need the Math.PI field when making trigonometric calculations.
Math.sin()
The Math.sin() method calculates the sine value of some angle value in radians. Here is a Java Math.sin() exam- ple: double sin = Math.sin(Math.PI); System.out.println("sin = " + sin);
Math.cos()
The Math.cos() method calculates the cosine value of some angle value in radians. Here is a Java Math.cos() ex- ample: double cos = Math.cos(Math.PI); System.out.println("cos = " + cos);
Math.tan()
The Math.tan() method calculates the tangens value of some angle value in radians. Here is a Java Math.tan() ex- ample: double tan = Math.tan(Math.PI); System.out.println("tan = " + tan);