Operator | Performs |
+ | Additon (also used for String concatenation) |
- | Subtraction |
/ | Division |
* | Multiplication |
% | Gives Remainder |
++ | Pre or post increment |
-- | Pre or post decrement |
class ArithmeticOperation{ public static void main(String args[]){ int operand1 = 30; int operand2 = 10; System.out.println("Addition of operand1 and operand2 is " + (operand1 + operand2)); System.out.println("Subtraction of operand1 and operand2 is " + (operand1 - operand2)); System.out.println("Multiplication of operand1 and operand2 is " + (operand1 * operand2)); System.out.println("Division of operand1 and operand2 is " + (operand1 / operand2)); System.out.println("Remainder of operand1 and operand2 is " + (operand1 % operand2)); } }
Output
Addition of operand1 and operand2 is 40 Subtraction of operand1 and operand2 is 20 Multiplication of operand1 and operand2 is 300 Division of operand1 and operand2 is 3 Remainder of operand1 and operand2 is 0
Some
points to be Noted
1.
Multiplication, Division and remainder operators has more priority
than Addition and Subtraction operators.
Example
class ArithmeticPriority{ public static void main(String args[]){ int var1 = 10, var2 = 20; int result = var1+var2*var1; System.out.println(result); result = var1-var2/var1; System.out.println(result); result = var1+var2%var1; System.out.println(result); } }
Output
210 8 10
Explanation
for
the Expression
result
= var1+var2*var1
= 10 + 20*10
= 10 +200
= 210
result
= var1-var2/var1
= 10-20/10
= 10-2
= 8
result
= var1+var2%var1
= 10 + 20 % 10
= 10 + 0
= 10
2.
Remainder operator always returns the sign of numerator
Ex:
5
% 2 = 1
-5
% 2 = -1
class RemainderEx{ public static void main(String args[]){ int var1 = 25, var2 = 10; System.out.println(var1%var2); var1= -25; System.out.println(var1%var2); } }
Operators In Java Arithmetic Operators: ++, -- Home
No comments:
Post a Comment