☞Following are the types of arithmetic operators in java.
* ➺ Multiplication / ➺ Division (quotient) % ➺ Modulus (remainder) + ➺ Addition - ➺ Subtraction
☞+ and - are unary as well as binary operators.
☞*, /, and % are binary operators.
☞Precedence of arithmetic operators.
+ - ++ -- ➺ unary operators * / % ➺ binary operators + - ➺ binary operators
☞It is used to indicate sign of a number.
☞Example : +5, +a, -6, -b etc
public class UnaryExample { public static void main(String[] args) { int a=+10; int b=-20; System.out.println(a); System.out.println(-a); System.out.println(b); System.out.println(-b); } }
10 -10 -20 20
☞Increment operator increases value of the operand by 1.
☞They are of two types.
1. Post Increment (x++) ➺ Change after the action 2. Pre Increment (++x) ➺ Change before action
☞x++ and ++x means x=x+1
public class PostExample1 { public static void main(String[] args) { int x=3; x++; System.out.println(x); } }
4
public class PreExample1 { public static void main(String[] args) { int x=3; ++x; System.out.println(x); } }
4
public class PostExample2 { public static void main(String[] args) { int x=3,y; y=x++; System.out.println(x+" "+y); } }
4 3
public class PreExample2 { public static void main(String[] args) { int x=3,y; y=++x; System.out.println(x+" "+y); } }
4 4
☞Increment operator decreases value of the operand by 1.
☞They are of two types.
1. Post Decrement (x--) ➺ Change after the action 2. Pre Decrement (--x) ➺ Change before action
☞x-- and --x means x=x-1
public class PostExample1 { public static void main(String[] args) { int x=3; x--; System.out.println(x); } }
2
public class PreExample1 { public static void main(String[] args) { int x=3; --x; System.out.println(x); } }
2
public class PostExample2 { public static void main(String[] args) { int x=3,y; y=x--; System.out.println(x+" "+y); } }
2 3
public class PreExample2 { public static void main(String[] args) { int x=3,y; y=--x; System.out.println(x+" "+y); } }
2 2
☞Priority of *, /, % is same but higher than +, - operators.
☞Similarly, priority of + and – is same.
☞ If the single expression has more than one arithmetic operators of same priority, they will be evaluated from left to right in the expression using associativity rule.
public class ArithmeticExample { public static void main(String[] args) { int x=5, y=10; System.out.println(x * y); System.out.println(x / y); System.out.println(x % y); System.out.println(x + y); System.out.println(x - y); System.out.println("-------"); System.out.println(2 * 3 / 5); System.out.println(2 / 3 * 5); System.out.println(5 + 5 * 5 / 5 - 5); } }
50 0 5 15 -5 ------- 1 0 5