Java: Arithmetic Operators

This lesson will go over the basic arithmetic operators that help you perform addition, subtraction, multiplication, division, and also the assignment operator.

The Assignment Operator

It is very important to understand that the “=” sign has a very different purpose and meaning in programming and Math. The ‘=’ sign is an assignment operator in programming. In simple words, it implies that the variable situated on the right side of the operator is assigned the value placed on the left side of the “=” sign.  

Consequently, while working on Java, understand that x = z is different from z = x. Here is an example that can demonstrate the difference. Let us take two variables with names x and z and declare them as follows:  

int x = 9;
int z = 29;

Now, if x is set equal to z, 

x = z;

A math teacher may not be very happy with these claims, as x is not equal to z. Nevertheless, in programming, this can make complete sense.   

This statement implies that the value held within z is assigned to x. Basically, a value held by one variable can be assigned to another.

In the example, while z remains the same, x becomes 29. So, both x and z are now 29.

However, change x to 17 and z to 82 in this manner,

x = 17;
z = 82;

and then use the assignment operator in this way

z = x;

The value of x is assigned to z. Thus, x remains unchanged, while z takes up the value of x, making both x and z equal to 17. 

Basic Operators

While one major use of operators is to assign a value to a variable through initialization or assign a variable to another, they are also used to perform mathematical functions. The most commonly used operators to perform mathematical functions in Java are +, -, *, / and %, which add, subtract, multiply, divide and return the remainder after division, respectively.  


If a = 43 and b = 11, then
Addition:       a + b = 54
Subtraction:    a - b = 32 
Multiplication: a*b = 473
Division:       a/b = 3 (rounded down to the nearest whole integer)
Modulus:        a%b = 10 (the remainder when 43 is divided by 11)

If ‘a’ and ‘b’ are both integers, then the answer will also be an integer. However, even if one of the two variables is a non-integer, the answer will also be a non-integer. For example,

9 / 3 = 3
9.0 / 3 = 3.0
9 / 3.0 = 3.0
9.0 / 3.0 = 3.0

To explain this further, in the first example, both the numbers used were integers, which is why the answer was also an integer. Moreover, in case there are any digits after the decimal point, truncation occurs. 

In other examples, at least one of the numbers used is a non-integer, thereby giving a non-integer as an answer.  

It is important to remember that 9 and 9.0 are two different numbers in Java. While the former is an integer, the latter is a floating-point number.

Leave a Reply

%d bloggers like this: