Code tracing: "what does this print?"
Computer Science · Java
Question 1 of 10
0What does this Java code print? int x = 7; x += 5; System.out.println(x);
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Code tracing: "what does this print?" explained
Code tracing means working out what a program prints by following it line by line, without running it. You track each variable's value and apply the language's rules for types, operators and string joining.
In Java, the types of the operands decide the result. Dividing two int values gives an int, so the fraction is dropped. Once a String is involved, the + operator joins text instead of adding numbers, and it groups from left to right.
public class Trace {
public static void main(String[] args) {
int a = 7;
int b = 2;
System.out.println(a / b);
System.out.println(a / (double) b);
System.out.println(a % b);
System.out.println(1 + 2 + "Java");
}
}
Caveat: the public class must match the file name Trace.java. Other classes in the same file can have any names.
Worked example
Trace each println in order.
- a / b is 7 / 2 with ints, giving 3.
- The cast (double) makes the divisor 2.0, so the result is 3.5.
- 7 % 2 is the remainder, 1.
- 1 + 2 is the int 3, and 3 + "Java" joins into "3Java".
The program prints 3, 3.5, 1 and 3Java, one per line.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Java code print? int x = 4; x += 5; System.out.println(x);
Medium
What does this Java code print? int n = 3; System.out.println(n * 6);
Hard
What does this Java code print? int x = 9; x += 5; x *= 3; System.out.println(x - 4);