Arithmetic Operations in Java

The following arithmetic operators are available in Java:


+ addition

- subtraction

* multiplication

/ division

% modulus


Java provides the ++ and -- operators, which, respectively, increment and decrement the operand. So a++ is equivalent to a = a + 1. If ++ or -- is postfixed to the operand, the result is evaluated before the increment or decrement. If ++ or -- is prefixed, the result is evaluated after the increment or decrement. The code in the Arithmetic example illustrates this.


Arithmetic

public class Arithmetic
{
public static void main(String[] args)
{
int a1=2;
int a2=2;
int a3=2;
int a4=2;
int b;
int c;
int d;
int e;
b=a1++;
c=++a2;
d=a3--;
e=--a4;

System.out.println (''a1 = " + a1 + " b = " +b );
System.out.println (''a2 = " + a2 + " c = " +c );
System.out.println (''a3 = " + a3 + " d = " +d );
System.out.println (''a4 = " + a4 + " e = " +e );

}
}


The output of the Arithmetic application is as follows:

> java Arithmetic
a1 = 3 b = 2 a2 = 3 c = 3 a3 = 1 d = 2 a4 = 1 e = 1


This idea is extended by the +=, -=, *=, /=, and %= operands to combine an operation with an assignment. Thus,

a += 2 is equivalent to a = a + 2
a -= 2 is equivalent to a = a - 2
a *= 2 is equivalent to a = a * 2
a /= 2 is equivalent to a = a / 2
a %= 2 is equivalent to a = a % 2


When an expression consists of two or more operators, Java applies rules of precedence about which operand is applied first. Operands with a higher precedence are applied before those of a lower precedence. The operands *, /, and % are of equal precedence, and are of higher precedence than + and -. Consequently,

8 * 4 - 2 is equivalent to (8 * 4) - 2, which equals 30

8 + 4 / 2 is equivalent to 8 + (4 / 2), which equals 10


Of course, you can use parentheses to override this default behavior. Thus,

8 * (4 - 2) will evaluate to 16

(8 + 4) / 2 will evaluate to 6


Where an expression consists of two or more operators of equal precedence, Java will in general evaluate the operands from left to right. For example,

8 / 4 * 2 is equivalent to (8 / 4) * 2, which equals 4

and not 8 / (4 * 2), which equals 1



The / and * operators are said to associate from left to right. A few operators associate from right to left. Appendix A lists all the operator associativity rules.

No comments:

Post a Comment