Showing posts with label Arithmetic Operators. Show all posts
Showing posts with label Arithmetic Operators. Show all posts

Thursday, 28 May 2015

Java Arithmetic Operators

Java has five arithmetic operators:

  1. + (Addition)
  2. - (Subtraction)
  3.  * (Multiplication)
  4. / (Division) and
  5. % (Modulus)

The operands can be integers, floating-points or both. The arithmetic operators can be applied on

all the primitive types except the boolean. If a binary operator is used to combine two operands

of similar type then the type of result will also be same. But if a binary operator is used to

combine operands of different types then operand of lower type gets converted to the higher type

before the evaluation and the type of the result will be same as that of operand of higher type.

The type conversion rules are discussed in a subsequent section.



The behavior of the +, -, *, and / operator is same as in C/C++. The modulus operator can be

applied to integer as well as floating-point types while in case of C/C++ it can be applied to

integer types only. For example the following is valid in Java:

6.4 % 2.1

The result of the above expression will be 0.1.


Arithmetic Assignment Operators

The Java supports the following Assignment Operators like C/C++:

+=, -=, *=, /=, %=

An assignment operator has the following syntax:

<variable><operator> = <expression>

The above assignment is equivalent to:

<variable> = <variable>  <operator> (<expression>)

For example the assignment:

 x += 5 is equivalent to x = x + 5

For example the assignment:

 x += a * c is equivalent to x = x + (a*c)