AP Computer Science A · Using objects and methods
Expressions and assignment
1Arithmetic operators
Java's arithmetic operators are +, -, *, / and % (remainder).
- Integer division: if both operands are
int, the result is anintand the decimal part is truncated (cut off, not rounded).7 / 2is3;-7 / 2is-3. - If at least one operand is
double, the result isdouble:7 / 2.0is3.5. - Remainder:
17 % 5is2;8 % 2is0. Usen % 2 == 0to test for even numbers. - Dividing an
intby zero throws an ArithmeticException.
Operator precedence: *, /, % before +, -; left to right for equal precedence; parentheses first.
Check yourself
What is the value of 17 / 5 * 2?
Show the answer
6
17 / 5 = 3, then 3 * 2.
2Assignment and compound operators
The assignment operator = evaluates the right side, then stores it in the variable on the left:
int total = 5;
total = total + 3; // total is now 8
Compound operators combine both steps: x += 3; x -= 2; x *= 4; x /= 2; x %= 3;
Increment and decrement: x++ adds 1; x-- subtracts 1.
trace the code.
int a = 10;→ a = 10.a -= 4;→ a = 6.a *= 3;→ a = 18.a %= 5;→ a = 3.
Trace assignments one line at a time, recording each new value
Check yourself
After int n = 7; n %= 3; n++; what is n?
Show the answer
2
7 % 3 = 1, then 2.
3Casting
A cast converts a value to another type:
(int) 7.9gives7(truncates toward zero).(double) 7gives7.0.- To round a positive double to the nearest int:
(int) (x + 0.5); for negative values:(int) (x - 0.5).
Java widens automatically from int to double (double d = 5; stores 5.0) but not the other way: int n = 5.0; is a compile-time error.
average of two ints.
int a = 7, b = 8;double avg = (a + b) / 2;gives 7.0 (integer division happened first).double avg = (a + b) / 2.0;gives 7.5. So does(double) (a + b) / 2.
Check yourself
What is (int) 3.99 + (int) 2.5?
Show the answer
5
3 + 2.
4Common pitfalls
- Integer division in averages and percentages:
count / total * 100gives 0 ifcount < total. Write100.0 * count / total. - Casting too late:
(double) (7 / 2)is3.0, not3.5. doublearithmetic can produce tiny round-off errors:0.1 + 0.2is not exactly0.3.
Check yourself
What does (double) (9 / 4) evaluate to?
Show the answer
2.0
Division happens first.
5Going deeper: integer division, the remainder operator, casting and tracing
Operator precedence (highest first)
- Parentheses.
- Unary minus,
!, casts,++and--. *,/,%.+,-.- Relational: less than, greater than and their or-equal forms.
==,!=.&&, then||.- Assignment (
=,+=, …), which is evaluated last and from right to left.
Operators of equal precedence are evaluated left to right.
Integer division truncates toward zero
7 / 2is 3.-7 / 2is −3.1 / 2is 0.- If either operand is a double, the division is real:
7 / 2.0is 3.5. - Dividing an int by zero throws an ArithmeticException.
The remainder operator %
7 % 2is 1.10 % 5is 0.3 % 7is 3.- The result takes the sign of the left operand:
-7 % 2is −1.
Uses of % and /
- Even or odd:
n % 2 == 0. - Divisibility:
n % k == 0. - Last digit:
n % 10. Remove the last digit:n / 10. - Wrap around:
(index + 1) % lengthreturns to 0 after the last position. - Unit conversion: 137 minutes is
137 / 60hours and137 % 60minutes: 2 h 17 min.
Worked example (sum of digits): trace for n = 472.
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
- n = 472: add 2; sum = 2; n = 47.
- n = 47: add 7; sum = 9; n = 4.
- n = 4: add 4; sum = 13; n = 0.
- Loop ends. sum = 13.
Casting
(double) a / b: the cast applies toafirst, so the division is real.(double) (a / b): the int division happens first; the cast only adds.0.- With a = 7, b = 2: the first gives 3.5; the second gives 3.0.
(int) 3.99is 3: truncation.
Rounding to the nearest integer
- Positive values:
(int) (x + 0.5). - Negative values:
(int) (x - 0.5). - Rounding 3.5 gives
(int) 4.0= 4; rounding −3.5 gives(int) -4.0= −4.
Compound assignment: x += 3 means x = x + 3; likewise -=, *=, /=, %=. x++ adds 1; x-- subtracts 1. (On the exam these appear as statements on their own.)
String concatenation: + with a String joins. Evaluation is still left to right.
"Sum: " + 2 + 3is"Sum: 23".2 + 3 + " is the sum"is"5 is the sum"."Sum: " + (2 + 3)is"Sum: 5".
Worked example (trace): what is printed?
int a = 17;
int b = 5;
double c = a / b;
a %= b;
b += a * 2;
System.out.println(a + " " + b + " " + c);
a / bis int division: 3, stored as 3.0.a %= b: a = 17 % 5 = 2.b += a * 2: b = 5 + 4 = 9.- Output:
2 9 3.0.
Worked example (average): scores total 257 from 3 tests.
257 / 3gives 85: the fraction is lost.(double) 257 / 3gives 85.666…257 / 3.0also works.
Common mistakes
- Forgetting that
/between two ints discards the fraction. - Casting the result in place of an operand.
- Assuming
%is always non-negative. - Expecting
"Total: " + 1 + 2to print 3. - Writing
=(assignment) where==(comparison) is meant.
Check yourself
What is the value of (double) (9 / 2)?
Show the answer
4.0
The integer division happens inside the parentheses before the cast.
6For top marks
- Trace expressions step by step, writing the type and value of each sub-expression.
- Watch for integer division whenever two
intvalues are divided. - Use
%for divisibility, even/odd tests and extracting digits (n % 10is the last digit;n / 10removes it). - Remember
(int)truncates; it does not round.
to get the tens digit of a positive int n, use (n / 10) % 10.
Check yourself
For n = 4728, what is (n / 10) % 10?
Show the answer
2
472 % 10.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera