SEN1001 · Week 8 · Review + Midterm

Midterm review: weeks 1-7

A one-table summary of all the midterm topics from the compile chain to ArrayList, the traps that cost the most points, exam tactics and mixed exam-style questions.

trace tableoutput tracingpartial creditinteger divisionshort-circuitfall-throughoff-by-onepass-by-valuereferenceoverloadingArrayList

The midterm covers the first seven weeks: how Java is compiled and run, variables and operators, Scanner and String, decision structures, loops, methods and arrays (ArrayList included). This page does not teach anything new; it collects the scattered rules in one place and lists the traps that cost the most points. The questions at the end mix the topics, just like the real exam.

First read the summary table, then solve the questions with pen and paper. For every question you get wrong, go back to its topic and reread the “Common mistakes” table on that page.

One-table summary

WeekTopicThe core you need to know
1Compiling and runningjavac Hello.java → Hello.class (bytecode) → java Hello → JVM. Three error types: compile-time (;, name, type), runtime (/ by zero, array bounds), logic (wrong result).
2Variables, types, printf8 primitives. Widening is automatic, narrowing needs a cast; a cast truncates. char + int = int. printf %d %.2f %s %n, %5d width.
2Scanner, String, ++nextLine after nextInt returns empty. charAt returns char, substring(a, b) excludes b, compare with equals. x++ old value, ++x new value.
2Operatorsint division truncates, the sign of % comes from the left, * / % first, the same level goes left to right, String + concatenates left to right.
3if/else, switchIn else if, the first true branch. Short-circuit. In switch, no break means fall-through.
4Loopswhile 0+ iterations, do-while 1+ iterations. break/continue. In nested loops the inner loop restarts on every outer iteration.
5MethodsHeader, return, void. Pass-by-value. Scope. Overloading: same name, different parameter list. Math and the Random range.
6Arraysnew int[n], index 0..n-1, length. Enhanced for reads. An array goes to a method as a reference.
7Algorithms, ArrayListSearch -1, in-place reversal up to half, b = a alias. ArrayList: size, get, set, add, remove.

The ten most expensive traps

These take the most points. Each one was explained in detail on an earlier page.

#TrapThe truth
1double d = 7 / 2; → 3.53.0, the division was done as int
2"Sum: " + 3 + 4 → Sum: 7Sum: 34, concatenation from left to right
3if (s == "yes")s.equals("yes")
4No break in a switch, only the matching case runsEverything below runs
5for (i = 0; i <= n; i++) n iterationsn + 1 iterations
6After the loop the counter is the last value usedThe value that broke the condition
7When a method changes a parameter, the variable in main changesIt does not change (pass-by-value)
8A method cannot change an arrayIt can change its elements
9Math.sqrt(16) → 44.0
10In nested loops iterations = outer × inner alwaysIf the inner bound depends on the outer variable, count iteration by iteration

Exam tactics

Output (tracing) questions: Draw a trace table in the margin of the paper: a column for each variable, one for the condition, one for what is written to the screen. Run the code line by line. When a variable changes, write the new value below. Tell print and println apart: after println comes a new line. Most mistakes are made in the first round, in the last round and in the value after leaving the loop; check these three separately.

Method writing questions: Partial credit comes in this order:

  1. Header: public static <return type> <name>(<type> <param>). If the answer is yes/no, boolean; if a number, int or double; if text, String; if it only prints, void.
  2. Initialize the result variable: int sum = 0;, int count = 0;, int max = arr[0];.
  3. The loop and the condition inside it.
  4. return (if not void), outside the loop.
  5. Test on paper with an example.

Even if you have no idea, write steps 1 and 2. A blank paper is zero points.

Error-finding questions: Scan in order: is there a ; at the end of each line, do the curly braces match, is every variable used defined in that block (scope), do the types match (double → int), is the String in double quotes, is the char in single quotes, is it = or == inside an if.

Worked mixed example 1: loop + condition

int total = 0;
for (int i = 1; i <= 4; i++) {
    if (i % 2 == 0) total += i * i;
    else total -= i;
}
System.out.println(total);
i   i % 2 == 0 ?   operation        total
1   F              total -= 1       -1
2   T              total += 4        3
3   F              total -= 3        0
4   T              total += 16      16
5   condition 5 <= 4 F → exit
16

Worked mixed example 2: method + array + pass-by-value

static int f(int[] a, int k) {
    a[k] += 10;
    k++;
    return a[k];
}
// in main:
int[] arr = {5, 1, 4};
int k = 0;
System.out.println(f(arr, k) + " " + k + " " + arr[0]);
1 0 15

Think about three things separately:

  • a[0] += 10: because the array came by reference, arr[0] in main became 15.
  • k++: the method’s own copy of k became 1. The k in main stayed 0.
  • return a[1]: 1.

Three different rules work on the same line; a midterm question looks exactly like this.

Question type → which page to go back to

If you got a question wrong, find which rule you missed and go back to that page. The table below ties most questions to a single rule:

What you see in the questionThe rule to checkPage
/ and two intstruncates, does not roundOperators (week 2)
"..." + number + numberconcatenation from left to rightOperators, Scanner and String
x++ inside an expressionthe old value is usedScanner and String (week 2)
+ with a charthe result is intVariables (week 2)
an else if chainonly the first true branchif/else and switch (week 3)
++ on the right of && / ||short-circuitif/else and switch
switch, missing breakfall-throughif/else and switch
the inner loop bound depends on the outer variablecount iteration by iterationLoops (week 4)
a method changes a parameterpass-by-valueMethods (week 5)
a method changes an array elementreference, the caller sees itArrays (week 6)
b = a then b[i] = ...aliasArray algorithms (week 7)
remove(number) in an Integer listdeletes the indexArray algorithms and ArrayList

Last-night checklist

  • Can you write the three Scanner lines (import, new, nextInt) from memory?
  • Can you explain the difference between 1 + 2 + "A" and "A" + 1 + 2?
  • Can you write the left-aligned, inverted and right-aligned star triangles with their loop bounds?
  • Can you write the methods isPrime, sumDigits, max, countDivisors, getSeason without looking?
  • Can you write methods that find the sum, the average (double!) and the maximum of an array?
  • Do you know the difference between remove(1) and remove(Integer.valueOf(1))?

If you say yes to all of them, solve the questions below and note down your mistakes.

Common mistakes

Wrong ideaThe truth
Computing in your head is enough in tracingDraw a trace table; first round, last round and after the loop
print and println are the sameprint stays on the line
In a writing question only full code gets pointsThe header and the loop earn partial credit
In a do-while, continue goes back to the start of the bodyIt goes to the condition
If there is no method taking a char, it does not compilechar widens to int
A long argument goes to an int methodThere is no narrowing; it widens to double
A variable declared inside a block still exists afterwardsThe scope ends, cannot find symbol

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1medium

What is printed?

System.out.println(5 + 7 / 2 * 2 + "x" + 5 % 3);
Show answer
11x2

First * / %: 7 / 2 = 3, 3 * 2 = 6, 5 % 3 = 2. Then + from left to right: 5 + 6 = 11 (a number), 11 + "x" = "11x", "11x" + 2 = "11x2".

Question 2hard

What is printed?

int a = 3;
int b = a++ * 2 + --a;
System.out.println(a + " " + b);
Show answer
3 9

Left to right: a++ gives the value 3, a = 4. 3 * 2 = 6. --a decrements first: a = 3, the value is 3. b = 6 + 3 = 9.

Question 3medium

What is printed?

char c = 'b';
int x = 0;
switch (c) {
    case 'a': x += 1;
    case 'b': x += 2;
    case 'c': x += 3; break;
    default: x += 10;
}
System.out.println(x);
Show answer
5

It enters at case 'b': x = 2. There is no break, it falls into case 'c': x = 5, break. case 'a' stays above so it does not run, and default is not reached.

Question 4medium

What is printed?

int pairs = 0;
for (int i = 1; i <= 4; i++)
    for (int j = i + 1; j <= 4; j++)
        if ((i + j) % 2 == 1) pairs++;
System.out.println(pairs);
Show answer
4

The pairs with i < j: (1,2) (1,3) (1,4) (2,3) (2,4) (3,4). The ones whose sum is odd: (1,2)=3, (1,4)=5, (2,3)=5, (3,4)=7. Four pairs.

Question 5hard

What is printed?

int n = 3, s = 0;
do {
    n--;
    if (n == 1) continue;
    s += n;
} while (n > 0);
System.out.println(n + " " + s);
Show answer
0 2

Round 1: n = 2, s = 2, condition 2 > 0 T. Round 2: n = 1, continue → in a do-while, continue jumps straight to the condition: 1 > 0 T. Round 3: n = 0, s = 2 + 0 = 2, 0 > 0 F → exit.

Question 6hard

What is printed?

static int f(int[] a, int k) {
    a[k] += 10;
    k++;
    return a[k];
}
// in main:
int[] arr = {2, 4, 6, 8};
int idx = 1;
int r = f(arr, idx);
System.out.println(r + " " + idx + " " + arr[1]);
Show answer
6 1 14

The array goes as a reference: a[1] += 10 changes the array in main, arr[1] = 14. k is an int, its copy is incremented; idx in main stays 1. The method returns a[2] = 6.

Question 7medium

What is printed?

String w = "Programming";
int cnt = 0;
for (int i = 0; i < w.length(); i++) {
    if (w.charAt(i) == 'm' || w.charAt(i) == 'g') cnt++;
}
System.out.println(cnt + " " + w.indexOf('g') + " " + w.substring(3, 6));
Show answer
4 3 gra

P0 r1 o2 g3 r4 a5 m6 m7 i8 n9 g10. Two m's, two g's: 4. The first g is at index 3. substring(3, 6) → 3, 4, 5: "gra".

Question 8medium

What is printed?

ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 4; i++) list.add(i * i);
list.add(1, 7);
list.remove(Integer.valueOf(4));
System.out.println(list + " " + list.get(2));
Show answer
[0, 7, 1, 9] 1

The loop: [0, 1, 4, 9]. add(1, 7): [0, 7, 1, 4, 9]. Delete the value 4: [0, 7, 1, 9]. get(2) = 1.

Question 9hard

Only these two methods exist. What is printed?

static String t(int x)    { return "I" + x; }
static String t(double x) { return "D" + x; }
// in main:
System.out.println(t('A'));
System.out.println(t(5L));
System.out.println(t(9 / 2));
Show answer
I65
D5.0
I4

There is no exact match for char; char widens to int, 'A' = 65 → t(int). long cannot be narrowed to int but widens to double → "D5.0". 9 / 2 = 4 (int) → t(int).

Question 10easy

What is printed?

double avg = 0;
int[] m = {7, 8, 10};
for (int v : m) avg += v;
avg /= m.length;
System.out.printf("%.2f %d%n", avg, (int) avg);
Show answer
8.33 8

Since avg is a double, the sum is 25.0, and the division is a double division: 25.0 / 3 = 8.333... %.2f → 8.33. The cast truncates: 8.

Question 11medium

Find the compile-time error. Which line is it, and why?

int total = 0;
for (int i = 0; i < 3; i++) {
    int sq = i * i;
    total += sq;
}
double avg = total / 3;
String msg = "avg";
if (msg == "avg") System.out.println(sq);
Show answer
Last line: sq cannot be found (scope)

sq was declared inside the loop block and disappears when the block ends: cannot find symbol. The other two lines compile but are bad: total / 3 is int division (risk of a logic error), and msg == "avg" compares a String with == (equals should be used).

Question 12hard

Write a static method isPalindrome(int n) that returns true if a non-negative integer reads the same backwards (e.g. 1221).

Show answer
build rev with rev = rev * 10 + n % 10, then return rev == original;

Because n goes down to 0 in the loop, save the original value at the start.public static boolean isPalindrome(int n) { int original = n, rev = 0; while (n > 0) { rev = rev * 10 + n % 10; n /= 10; } return rev == original;}Test: 1221 → true, 123 → false, 7 → true.

Verification: All questions and worked examples were run with JDK 26 (verify/SEN1001/W08.java). The error-finding question was checked by compiling verify/SEN1001/err/Find.java with javac.

Review card

.java → javac → .class (bytecode) → java → JVM compile / runtime / logic int/int truncates (double) cast first "A"+1+2="A12" 1+2+"A"="3A" char+int=int x++ old value ++x new value x += 2.7 hidden cast *= takes the right side as a whole %.2f rounds (int) truncates Math.round(2.5)=3 pow/sqrt/ceil/floor return double else if: first true without { } one statement else goes to the nearest if = vs == && || short-circuit: a ++ on the right may not run switch: falls through to break, default included continue in do-while → condition Rounds: i<n → n i<=n → n+1 when from 1 (from 0 with <=n → n+1) counter after the loop is one more break ends the inner loop for(...); empty body Method: header + return on every path pass-by-value overload: exact match → widening Array: 0..length-1, default 0/null, b = a alias, a method can change the elements ArrayList<Integer>: size() get set add remove(index) remove(Integer.valueOf(x)) String: equals, charAt returns char, substring b excluded, indexOf -1 if absent Tactic: trace table, check the first and last round separately, in a writing question header + loop + return