The Arithmetic operators are used to perform arithmetic operations on numeric values of type int, float, double, short and byte. Assignment operators are also considered as arithmetic operators.
Here is the complete list of arithmetic operators:
Operator | Result |
+ | Addition |
– | Subtraction (also unary minus) |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
+= | Addition assignment |
-= | Subtraction assignment |
*= | Multiplication assignment |
/= | Division assignment |
%= | Modulus assignment |
— | Decrement |
An assignment statement has three elements:
- The variable to store the result,
- The assignment operator: =,
- An arithmetic expression
For Example, Here the assignment operator will add value 5 on the previous value of a.
int a=1;
a+=5;
See Also :
Arithmetic Operators Example
public class ArithmaticOperatorTest { public static void main(String[] args) { ArithmaticOperatorTest test=new ArithmaticOperatorTest(); test.testArithmaticOperatorWithIntegers(); test.testArithmaticOperatorWithFloat(); test.testModulusOperator(); test.testAssignmentOperators(); } public void testArithmaticOperatorWithIntegers() { // arithmetic using integers System.out.println("Integer Arithmetic Operations"); int a = 2 + 2; int b = a * 3; int c = b / 5; int d = c - a; int e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); } public void testArithmaticOperatorWithFloat() { int a=2; // arithmetic using doubles System.out.println("\nFloating Point Arithmetic Operations"); double da = 2 + 2; double db = da * 3; double dc = db / 5; double dd = dc - a; double de = -dd; System.out.println("da = " + da); System.out.println("db = " + db); System.out.println("dc = " + dc); System.out.println("dd = " + dd); System.out.println("de = " + de); } public void testModulusOperator() { //Modulus :Modulus operator %: obtain the remainder after a division System.out.println("\nModulus Arithmetic Operator"); int a = 5 % 2; int b = 13 % 3; int c = 8 % -3; System.out.println(a); System.out.println(b); System.out.println(c); } public void testAssignmentOperator() { System.out.println("Assignment Operators"); int a = 1; int b = 2; int c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } }
Output
Integer Arithmetic Operations
a = 4
b = 12
c = 2
d = -2
e = 2
Floating Point Arithmetic Operations
da = 4.0
db = 12.0
dc = 2.4
dd = 0.3999999999999999
de = -0.3999999999999999
Modulus Arithmetic Operator
1
1
2
Assignment Operators
5
8
43
7
You must log in to post a comment.