← all problems

Unit 1 Review: Tough Expressions 🌶️🌶️

The hardest kind of Unit 1 multiple-choice question: an expression that mixes operators, casts, String concatenation and calls to methods you can read. Evaluate each one exactly as Java does: follow precedence, do an int division with ints and a double division with doubles, and work from the inside out. For double results write the value the way println would show it (5.0). For text results, write just the characters with no quotation marks.

Every question here is written inside a class that has these methods:

public static int sq(int n) { return n * n; }public static int half(int n) { return n / 2; }public static double avg(int a, int b) { return (a + b) / 2; }public static int bump(int n) { n++; return n; }public static String tag(String s, int n) { return s + n; }

Part 1: calls to the methods above.

1. What is the value of sq(half(9)) + sq(2)?

2. What is the value of avg(7, 4)? (The method returns a double. Look at what it does before it returns.)

3. What is the value of avg(7, 4) * 2?

4. What is the value of half(sq(5) + 1)?

5. What is the value of sq(bump(2)) - bump(sq(2))?

6. What does this print?

int n = 3; int m = bump(n) * bump(n); System.out.println(m + " " + n);

7. What is the value of tag("A", 1 + 2) + 4 + 5?

8. What does this print?

int x = 4; x = sq(x) - half(x); System.out.println(x);

Part 2: operators, casts and concatenation.

9. What is the value of 1 + 2 + "3" + 4 + 5?

10. What is the value of "" + 1 + 2 + 3 * 4?

11. What is the value of (double) 7 / 2 + 7 / 2?

12. What is the value of (double)(7 / 2) + 7 % 2 * 2?

13. What is the value of (int) 3.9 + (int) -3.9?

14. What is the value of (int)(2.5 3) - (int) 2.5 3?

15. What is the value of 5 / 2 + 5 / 2.0? (Write it as println would show it.)

16. What is the value of half(sq(3)) + half(7) * 2?

Part 3: sequences. Run the statements in order and give the final value. ++ and -- are used only as statements here.

17. What is the final value of a?

int a = 5; int b = a * 2; a++; b--; a = a + b;

18. What is the final value of c?

int c = 17; c %= 5; c *= c + 1; c -= sq(2);

19. What is the final value of s? (Just the characters.)

String s = "ab"; s += 1 + 2; s += tag("x", 3);

20. What is the final value of d?

int q = (int)(7.0 / 2) * 2; double d = q / 4;

Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.