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.
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
| Week | Topic | The core you need to know |
|---|---|---|
| 1 | Compiling and running | javac Hello.java → Hello.class (bytecode) → java Hello → JVM. Three error types: compile-time (;, name, type), runtime (/ by zero, array bounds), logic (wrong result). |
| 2 | Variables, types, printf | 8 primitives. Widening is automatic, narrowing needs a cast; a cast truncates. char + int = int. printf %d %.2f %s %n, %5d width. |
| 2 | Scanner, String, ++ | nextLine after nextInt returns empty. charAt returns char, substring(a, b) excludes b, compare with equals. x++ old value, ++x new value. |
| 2 | Operators | int division truncates, the sign of % comes from the left, * / % first, the same level goes left to right, String + concatenates left to right. |
| 3 | if/else, switch | In else if, the first true branch. Short-circuit. In switch, no break means fall-through. |
| 4 | Loops | while 0+ iterations, do-while 1+ iterations. break/continue. In nested loops the inner loop restarts on every outer iteration. |
| 5 | Methods | Header, return, void. Pass-by-value. Scope. Overloading: same name, different parameter list. Math and the Random range. |
| 6 | Arrays | new int[n], index 0..n-1, length. Enhanced for reads. An array goes to a method as a reference. |
| 7 | Algorithms, ArrayList | Search -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.
| # | Trap | The truth |
|---|---|---|
| 1 | double d = 7 / 2; → 3.5 | 3.0, the division was done as int |
| 2 | "Sum: " + 3 + 4 → Sum: 7 | Sum: 34, concatenation from left to right |
| 3 | if (s == "yes") | s.equals("yes") |
| 4 | No break in a switch, only the matching case runs | Everything below runs |
| 5 | for (i = 0; i <= n; i++) n iterations | n + 1 iterations |
| 6 | After the loop the counter is the last value used | The value that broke the condition |
| 7 | When a method changes a parameter, the variable in main changes | It does not change (pass-by-value) |
| 8 | A method cannot change an array | It can change its elements |
| 9 | Math.sqrt(16) → 4 | 4.0 |
| 10 | In nested loops iterations = outer × inner always | If 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:
- 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. - Initialize the result variable:
int sum = 0;,int count = 0;,int max = arr[0];. - The loop and the condition inside it.
- return (if not void), outside the loop.
- 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 question | The rule to check | Page |
|---|---|---|
/ and two ints | truncates, does not round | Operators (week 2) |
"..." + number + number | concatenation from left to right | Operators, Scanner and String |
x++ inside an expression | the old value is used | Scanner and String (week 2) |
+ with a char | the result is int | Variables (week 2) |
| an else if chain | only the first true branch | if/else and switch (week 3) |
++ on the right of && / || | short-circuit | if/else and switch |
| switch, missing break | fall-through | if/else and switch |
| the inner loop bound depends on the outer variable | count iteration by iteration | Loops (week 4) |
| a method changes a parameter | pass-by-value | Methods (week 5) |
| a method changes an array element | reference, the caller sees it | Arrays (week 6) |
b = a then b[i] = ... | alias | Array algorithms (week 7) |
remove(number) in an Integer list | deletes the index | Array 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)andremove(Integer.valueOf(1))?
If you say yes to all of them, solve the questions below and note down your mistakes.
Common mistakes
| Wrong idea | The truth |
|---|---|
| Computing in your head is enough in tracing | Draw a trace table; first round, last round and after the loop |
print and println are the same | print stays on the line |
| In a writing question only full code gets points | The header and the loop earn partial credit |
| In a do-while, continue goes back to the start of the body | It goes to the condition |
| If there is no method taking a char, it does not compile | char widens to int |
| A long argument goes to an int method | There is no narrowing; it widens to double |
| A variable declared inside a block still exists afterwards | The scope ends, cannot find symbol |
Test yourself
Exam-style questions. Solve them on paper first, then reveal the answer.
What is printed?
System.out.println(5 + 7 / 2 * 2 + "x" + 5 % 3);Show answer
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".
What is printed?
int a = 3;
int b = a++ * 2 + --a;
System.out.println(a + " " + b);Show answer
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.
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
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.
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
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.
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
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.
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
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.
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
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".
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
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.
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
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).
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
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.
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
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).
Write a static method isPalindrome(int n) that returns true if a non-negative integer reads the same backwards (e.g. 1221).
Show answer
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.