1. Arithmetic operators
We've seen how to define variables and assign different data types. Now, let's perform operations on data.
2. Operators
In programming, we often need to work with and modify variables. This can include performing calculations, and changing, or comparing values.
To achieve this, we use operators, which are built-in symbols that allow us to perform various tasks in our code.
Here, we will focus on arithmetic operators, used for calculations. We can use them when defining or updating the values of variables, or within print statements.
3. Addition using +
First, there is addition, represented by a plus sign.
We saw this briefly earlier in the course. Here, we add 5 and 6, assigning the result to an int variable called a.
Printing `a` shows the value of 11.
4. Addition using +
Addition works on all number types, such as here, where we add two doubles.
As we saw previously, it also works on Strings - there we know it as String concatenation!
5. Increment using ++
We can use two plus signs to increment, or add 1 to, the value.
For example, if we have a user’s age defined and they have a birthday, we can increment their age.
6. Subtraction using -
We can subtract using a hyphen, like so.
We can also decrement a value, decreasing it by one, using two hyphens. This can be useful for countdown tasks, such as a product launch date.
7. Multiply using *
To multiply numbers, we use an asterisk. Here, we multiply two variables, `price` and `quantity`, assigning the result to a new variable, `orderRevenue`.
If the two numbers are `integers`, the result of the multiplication will be an `integer`.
However, if one value is a `double`, the result will be a `double`.
8. Division using /
9. Division using /
Lastly, we can perform division using a forward slash.
Here, we divide the number of orders, 100, by the days of the month, 30, resulting in the average number of orders per day.
As the two numbers are integers, Java will return an integer, disregarding any decimals.
10. Division using /
If we want to return a double, then we can assign the result to a double, like so, or use a double as part of the calculation. Now we see the floating point numbers.
11. Recap
For your reference, this table recaps the syntax for each operator.
12. Let's practice!
Now you're equipped to perform calculations in Java, let's dive in!