Tutoriallearn.com
Easy Learning
Search Tutoriallearn.com :
| Operator | Purpose |
|---|---|
| + | Addition |
| - | Subtraction (Also Unary Minus) |
| * | Multiplication |
| / | Division |
| ++ | Increment |
| -- | Decrement |
| % | Modulus |
| += | Addition Assignment |
| -= | Subtraction Assignment |
| *= | Multiplication Assignment |
| /= | Division Assignment |
| %= | Modulus Assignment |
class ArithmeticExam {
public static void main(String args[]) {
int a = 10;
int b = 20;
int add, sub, mul, div, unaryminus;
add = a + b;
sub = b - a;
mul = a * b;
div = b / a;
unaryminus = -b;
System.out.println("add = " + add);
System.out.println("sub = " + sub);
System.out.println("mul = " + mul);
System.out.println("div = " + div);
System.out.println("unaryminus = " + unaryminus);
}
}
add = 30 sub = 10 mul = 200 div = 2 unaryminus = -20
public class ModulusProg {
public static void main(String args[]) {
int k = 62;
double m = 35.5;
System.out.println("k mod 10 = " + k % 10);
System.out.println("m mod 10 = " + m % 10);
}
}
k mod 10 = 2 m mod 10 = 5.5
class AssignOperator {
public static void main(String args[]) {
int a = 10;
int b = 30;
int c = 20;
int d = 40;
int k = 45;
// following are assignment operators
a += 5;
b -= 4;
c *= 3;
d /= 2;
k %= 4;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("k = " + k);
}
}
a = 15 b = 26 c = 60 d = 20 k = 1
Increment operator increases its operand by one.
x++;
is equivalent to
x = x + 1;
Increment operator can be used as both in prefix and postfix form.
In the prefix form, increment operator is written before the operand, such as:
++x;
In the postfix form, increment operator is written after the operand, such as:
x++;
Use of prefix and postfix form of increment operator is in the mathematical expression.
See the following assignment expression for both cases:
x = 1;
y = ++x;
In this prefix form , first value of x is incremented, then value of x is assigned to y variable.
Value of y is now 2 and value of x is now 2.
x = 1;
y = x++;
In this postfix form , first value of x is assigned to y variable, then value of x is incremented.
Value of y is now 1 and value of x is now 2.
class IncrementOp {
public static void main(String args[]) {
int x=1;
int y;
int m = 1;
int n;
y = ++x;
n = m++;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("m = " + m);
System.out.println("n = " + n);
}
}
x = 2 y = 2 m = 2 n = 1
class DecrementOp {
public static void main(String args[]) {
int x=1;
int y;
int m = 1;
int n;
y = --x;
n = m--;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("m = " + m);
System.out.println("n = " + n);
}
}
x = 0 y = 0 m = 0 n = 1