Arithmetic Operators in Java

Arithmetic Operators in Java

precedence and coercion

Arithmetic operators are Addition(+), Subtraction(-), Division(-) and Multiplication(*).

This type of operation can be applied to any type of data except Boolean.

There is a new operation known as a Mod(%) which is unfamiliar in our maths syllabus.

Let's look at how Mod works: Suppose you have to divide the number 20 by 3 as per your basic maths operation. Which operation you will perform and how you can write it?

18/3=X, In this case, X will be the answer and the answer after the calculation is 6. Here we called X as a Quotient and the remainder is 0.

Now there is a little change in the result while performing a Mod operation. Mod operation gives you the value of Remainder as a result, not a quotient.

Look at the following example: 18%3=X (Mod is denoted by %)

So what is the value of X? The value of X will be the remainder of a whole calculation and here remainder is 0.

In short, if you want a quotient, use the divide(/) operation and If you want remainder, then use a mod(%) operation.

18/3=6 This is a Divide operation and 18/3=0 This is a Mod operation

Note: Mod can perform on the float and double data type also.

Now, let's look at the precedence and how it works in Java.

Multiplication, division, and mod have the same and equal precedence but they have higher precedence compare to addition and subtraction. You can use parentheses to solve operations as per your preferences and also for changing the precedence of operators.

It is interesting to see the result of the operation of two different data types. The result of (Byte+byte), (int+int),(short+short), (byte+short), (byte+int),(short+int), will be Integer type only.

Here you can see the result different operations perform with different data types: Float+int=float long+float=float Char+short=int char=int=int Float=doble= double long +double= double

In this case, the compiler will internally convert the result of two different data types, which is known as coercion.

Important: Math. sqrt is used for finding out the root of the sum. Math. sqrt always gives values in double.