20 July 2020

How to do math in Java

Welcome to another tutorial on my "How To Code In Java" tutorial series. In the last tutorial, we went through the different ways of printing outputs in Java. In this tutorial, I'll be showing you how to do some maths in Java. I'll explain to you what's the symbol used for mathematics operation as well as the operator precedence. You'll also be learning about Java's "Math" class and variable value increment and decrement. 

Just like the regular mathematics that you've learned in school, every operator in mathematics operations has it's own group orders (precedences). When we calculate the mathematic operations, we'll follow the operator's group precedence. This is the same in programming, the mathematics operations are calculated in the same way we calculate numbers in maths. All numeric data type variables in Java could be used with the maths operation. But as for char data type, its somewhat confusing than the rest. So let's get started. 

Index for the tutorial:



Arithmetic operators precedence


the operator's precedence is ordered in the group as below:
  1. Parentheses,()
  2. Multiplication (*), Division (/) and Modulus (%)
  3. Addition (+) and Subtraction(-)

For group 2 and 3, there is another rule beside their precedence that we need to follow. As in mathematics that we usually use, they need to be done in the order from left to right. Now, you'll be wondering why does the symbol for multiplication isn't "x'. This is because "x" is a valid variable name. Therefore, if we use "x" in between two number, Java will think that we're using the value of variable "x" instead of treating it as a multiplication symbol. The modulus operators (%) is an operator that returns the remainder of a division instead of the quotient.

As for exponent and some other operation, there's no symbol for them. This is because it'll be hard to add them into the overcomplicated precedence table. Therefore, Java developer thinks that using a method is better than adding a new operator for these operations. Since it's much more convenient for them to change the implementation code for it in the future. That's why Java has the "Math" class to help programmers perform mathematics operation when using Java. Here's some example of doing maths operation in Java.


Some example on operator precedences.

The output of the code above

Now, pay attention to the last two statements. Their operator's position is in the same location, but both of their results are different. The difference in the code is that in the last example, I added parentheses to b * c. Since parentheses have the highest precedence, the operation in it will be performed first followed by the operation outside the parentheses. 


The Math class


The "Math" class is a class that lets programmers do many mathematical tasks onto numbers using the methods (functions) of the class. Some example is:

  • Math.sqrt(x) - give us the square root value of number x
    • Math.sqrt(64) will give us 8

  • Math.pow(x, y) - give us the value of x to the power of y
    • Math.pow(2, 3) will give us 8

  • Math.min(x, y) - compare two number and give us the smallest number.
    • Math.min(10, 12) will give us 10

  • Math.max(x, y) - compare two number and give us the biggest number.
    • Math.max(20, 40) will give us 40

  • Math.abs(x) - give us the absolute value of the number (convert negative number to positive number)
    • Math.abs(-13) will give us 13

  • Math.random() - giving us random number between 0.0 (inclusive) and 1.0 (exclusive)
    • (Math.random() * 13) will give us a real number value between 0.0 and 13.0 (excluding 13.0 and including 0.0)

The "Math" class could also do many more operation such as trigonometry, doing logarithm and many other operations. I'll make another tutorial on this topic so stay tuned for any updates.


Code sample for Math class methods


Code output



Example of a mathematical operation solution.

For an example of a mathematical operation, consider this:

((9 * 2) * 16 / 4) - Math.pow(2, 4)

When we output this mathematic operation, the Java will first complete the operation that's inside the parentheses first. In our case (9 * 2) which is in the outer parentheses operation ((9 * 2) * 16 / 4). After we have completed the inner parentheses operation (which give us 18), we then complete the outer parentheses operation using the left to right rule as there are only group 2 operators in the outer parentheses. 

This means that we will be multiplying 16 with 18 to get 288. Then, divide the result with 4, which produce 72. After the parentheses are completed, Java then will continue its operation from left to right. After we got 72, we can then minus the value with Math.pow(2,4), and we'll then get ourself the value 56.


Visualisation for the solution


Variable value increment and decrement.


In programming, we have a functionality where we could increase and decreases a variable value by 1 (one). This can be done by using the increment operator, ++ and decrement operator, --. We can use these two operators in two ways; postfix and prefix. Note that this functionality only available for primitive data types except for boolean data type variable. If you don't know what a primitive data type variable is, feel free to read on it in "What is a variable in Java" of this tutorial series. 

Here's the difference between postfix and prefix when using increment or decrement operator.


Differences between postfix and prefix


Using it with numeric data types.


To illustrate the difference between this two, imagine we initialised these variable:

The initialisation of variables.


Postfix


Now, let's look at an example of a postfix increment operation.


Postfix increment of the variables.


The output of code above.

As you can see, when we use postfix increment operation, Java would use the value of the variable first before increasing the value by 1 (one). In our case, Java would take the value of the variable and output the value first. Then, increase the variable value after that. When we print out the variable value for the second time, we will get the increased number value. 

This goes the same with decrement as well,

Postfix decrement of the variables.


The output of code above.

Prefix


So now let's go into prefix, prefix increment and decrement are just the opposite of postfix operation. Java would increase or decrease the value by one first then get the value for the operation that we're doing. In our case, the value of the variables would be increased first. Their value would then be used as an argument for the println() method. You can refer to the example below (We'll be using back the variables).


Prefix increment of the variables.

The output of code above.

This concept will also be the same for the prefix decrement operation.

Prefix decrement of the variables.


The output of code above


Using it with the char data type.


If you still remember that char could store positive numbers up to 65535? If yes then great, if no now you know it. The char variable could store either a number or a single character value (surrounded by single quote). 


The initialisation of variables.


Demonstrating math operation on the char variable.


The output for the code above


You'll notice in the code that I'm using some weird things like (int) and (char). These are called type-casting, where I can change the value data type into another data type. This functionality is handy because it lets us turn a char variable into an integer value during output (println,  printf, print, etc). When an operator ( +, -, *, /) is used onto a char, the integer value would be used to deal with the operation.

When adding two char data type variable, the returned value (the result that we get) will be in integer form. Therefore, if you want to output the symbol of that number, you'll need to use type-casting to convert the value from int to char. 

Since in Ascii, there are only 128 characters (0-127 for numbering), the number that exceeded number 127 will produce a question mark symbol.



Well, that's pretty much all the things that I want to teach you in this tutorial. I hope you now know how to do some mathematic operation in Java. As well as how to use increment and decrement onto variable in both prefix and postfix way. If you find this article helpful, don't forget to share it with others that might find it useful or interested in reading it. If you have any question, critics or suggestion for the blog, feel free to leave a comment down below. In the next tutorial, I'll be teaching you about "What is relational, shorthand and logical operators in Java?". So stay tuned. 

No comments:

Post a Comment