Arithmetic operators and precedence in C++ vs Java

Calculations form an integral part of programming.  Most of the tasks that the computer performs on our behalf are communicated to it in terms of mathematical expressions. Therefore, it is essential that we are well aware of how to manipulate numbers via arithmetic expressions in Java & C++. Let’s get started!

Arithmetic operators

There are 5 basic binary arithmetic operators offered by both programming languages. They are self-explanatory. But for the sake of completeness they are tabulated below.

Operator

Function

+

Adds the values on both sides of the operator

_

Subtracts the operand on the right hand side of the operator from the one on the left hand side

*

Multiplies the values on both sides of the operator

/

Divides the operand on the left hand side of the operator by the one on the right hand side

%

Divides the operand on the left hand side of the operator by the one on the right hand side and returns the remainder

The following code snippet shows how to use these operators in C++ and Java.

One important thing to note is that the following statement

in C++ stores 3 in the variable result instead of the correct answer 3.75. While the compiler computed the correct answer, the data type int of the variable result doesn’t allow us to store floating point values causing the implicit conversion and loss of data. Java, on the other hand, avoids such a mistake by giving you an error whenever a conversion might cause data loss. So one needs to be a bit more careful when selecting the data types of variables in C++.

Increment & Decrement Operators

Both C++ and Java inherently support increments and decrements by 1 using the following syntax:

These increment operators are used very frequently in loops. (we shall study about loops in a later lesson)

Operator precedence

In a mathematical expression involving multiple operations, the precedence of the involved operators must be kept in mind. For instance what do you think the following expression should yield as a result?

If the expression is scanned left to right the result is 42. However, since multiplication operator has a higher precedence, multiplication will be performed first followed by addition and the result will be 22. If you wish to perform addition first, you can enclose the addition operation within parenthesis.

The precedence of arithmetic operators is depicted in the figure below. Parenthesis has a higher precedence than any of the operators.

operator_precedence

Operator precedence in C++ and Java

A complete program

The following example shows Fahrenheit to Centigrade conversion in C++ and Java respectively. Note how proper brackets are necessary for correct output (212F =100C)

C++

Java

 

 

 

You may also like: