Arithmetic operators in java

Arithmetic operators in java

Arithmetic Operators :

You must be friendly arithmetic expressions in mathematics like  A-B. In this expression A and B are Operands and the subtraction sign is the operator. The same terminology is also used here in the programming language.

Type of Arithmetical Operators :

  1. Binary Arithmetical Operators
  2.  Unary Arithmetical Operators

Binary Arithmetical Operators :

OperationOperator (Symbol)SyntaxResult if a= 22, b=5
Addition+a+b27
Subtraction-a-b17
Multiplication*a*b110
Division/a/b4
Modulus/Remainder%a%b2
    

 Unary Arithmetical Operators :

OperatorUseDescription
++ Post - incrementA++

Post-increment: The value is assigned before the increment is made , e.g. 

A=1

B=A++

Then B will hold 1 and A will Hold 2

– Post-IncrementA--

Post-decrement: The value is assigned before the decrement is made , e.g. : 

A=1;

B=A--;

Then B will hold 1 and A will hold 0.

++ pre-Increment++A

Pre-Increment:  The value is assigned after the increment is made. e.g : 

A=1;

B=++A;

Then B will hold 2 and A will hold 2.

– pre-decrement--A

Pre-decrement: the value is assigned after the decrement is made, e.g: 

A=1;

B=--A;

Then B will hold 0 and will hold 0.

 

Solved Example :

int a=7,b=5;c;

c = ++a*4+b++;

System.out.println(c);

Ans: 37

 

int x=5; y=4; z ;

z = x*y++  +  ++x/y;

System.out.println(z);

Ans :21

 

int p=6,q=15, r;

r = (p*q) + p/q;

System.out.println(r);

Ans :10

 

int a=5, b=10, 

a = a+b++ + --b+b

System.out.println(a);

Ans :35

 

int m = 10, n=12, p;

p = (m++ *n++)+ --n/2;

System.out.println(p);

Ans :126

 

Order of precedence :

In Java, as in many programming languages, expressions within parentheses are evaluated first, followed by multiplication (*), division (/), and modulus (%) operators, and then addition (+) and subtraction (-) operators.

  1.            →      ()
  2.            →       * , % , /
  3.            →        + , -

Example : 

10+20/5-3*2

5*(10+5)+10-5

(6 + 2) * 3 - 5

10 - 3 * (5 + 2)

4 * (7 - 3) / 2 + 5

(10 + 4) / (7 - 2) * 3

8 * (6 + 2) - 4 / 2

6 - (3 * 2 + 4) / 2

(10 + 4) / (7 - 2) * 3

 

 


Share this article







Related Posts




0 Comments



Load more Comments

Post a Comment


helllo
Ocec Copyright text of dont't copyright our content