Arithmetic Operators
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
+
)-
)*
)/
)double area, price; int perimeter; area = 12.0 * 15.0; price = 45.00 / 2.0; perimeter = (300 * 2) + (160 * 2);
Review:
Can you identify all of the statements?
Can you identify all of the expressions? (Be careful!)
/
)%
)int
int
/
(in Java):
int
value that corresponds to the
truncation of the real-valued quotient
(i.e., the quotient rounded towards 0)%
(in Java):
x - (x/y)*y
x
is the dividend, y
is
the divisor, and /
is the integer
division operatorx - (x/y)*y
is not 0
)11 / 3
6 / 3
2 / 3
11 % 3
6 % 3
2 % 3
/
and %
Math.floorDiv()
and Math.floorMod()
+
)-
)++
)--
)++x
and
--x
) or after (in the case
of x++
and x--
) using it
int age, grade, penalty; age = +21; ++age; penalty = -20; grade = 100 + penalty;
++
(post) --
(post)++
(pre) --
(pre)
+
(unary) -
(unary)*
/
%
+
(binary) -
(binary)=
5 + 3 * 2
2 * 4 - 1
2 * (4 - 1)
2 + 8 + 3 - 2
8 * 4 * 2
8 / 4 / 2
double speed, distance, time; int area, width; int elapsed, hours, seconds; // mi/hr mi hr speed = distance / time; // in^2 in in area = width * width; // hr sec sec/hr hours = elapsed / 3600; // sec sec sec/hr seconds = elapsed % 3600;
int i, j; i = 3 + (j = 5);
j
and 8 is
assigned to i
int i, j; j = 0; i = 3 + j = 5; // Won't compile
+
has the highest precedence so 3 + j
is executed first and evaluates to 3
(a value)
5
is assigned to 3
and 3
isn't a variable