Skip to content
ExamSpine

Lesson 5.4 · Trace it

Trace: count in a word (Java)

Java code9 rows to fill3 marks

Complete the trace table for this Java code. word.charAt(i) is the character at index i, counting from 0, and word.length() is the number of characters. [3]

Line 1: String word = "noon";
Line 2: char first = word.charAt(0);
Line 3: int n = word.length();
Line 4: int count = 0;
Line 5: for (int i = 0; i < n; i++) {
Line 6, indented 1 level: if (word.charAt(i) == first) {
Line 7, indented 2 levels: count = count + 1;
Line 8, indented 1 level: }
Line 9: }
Line 10: System.out.println(count);

Fill in one row each time a line changes i or count, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Java shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.

Rowicountoutput
1
2
3
4
5
6
7
8
9