Variables, Data Types and Loops in Java: Worked Traces and Exam Traps

Learn to trace Java programs by tracking each variable's type, scope and current value through every condition and update.

KnowledgeGate Team

Exam prep & CS education

Updated 3 Dec 20266 min read
Variables, Data Types and Loops in Java: Worked Traces and Exam Traps

Java output questions become confusing when a variable changes on every iteration and an expression changes the result type. Reliable prediction starts by recording each variable's type, current value and scope, then checking the loop condition and update in order. The same method handles declarations, conversions, for, while and do-while loops, and mixed traces.

1. Variables are typed names whose values change

In int total;, Java declares a variable without assigning its first value. In int total = 3;, it declares and initialises it: int is the declared type, total is the identifier, and 3 is the initial value. A later statement such as total = total + 2; is reassignment, so total becomes 5.

Scope decides where that name can be used. If int total = 3; appears before a loop, total remains available after the loop. An int i = 1; declared in the loop header exists only within that loop construct. Most variables are mutable, but final int LIMIT = 4; cannot be reassigned after initialisation. For the wider language context, read the Java programming overview after mastering this vocabulary.

Table lists Java variables total, factor, active, grade and LIMIT with their declared types, current values, reassignment status, and a total update arrow.

2. Data types decide valid values and expression results

Java has eight primitive types. byte, short, int and long store whole numbers. float and double store decimal values. char stores one character, while boolean stores true or false. String is not a primitive. It is a reference type used for text.

Now follow the types through a calculation:

java
int items = 7;
double price = 12.5;
double bill = items * price;
int whole = (int) bill;
boolean eligible = whole >= 80;
char band = 'A';
String label = "A87";

The multiplication is 7 * 12.5 = 87.5, so bill is 87.5. The int value in items is widened for an operation whose result is a double. The explicit cast in (int) bill discards the fractional part, making whole equal to 87. It does not round to 88. Finally, 87 >= 80 is true, so eligible is true. Notice that 'A' is one char, while "A87" is a String containing three characters. These rules are Java rules, so always trace the operand types before applying a result remembered from another language. For the complete treatment of promotion, narrowing and cast placement, use the Java Operators and Type Conversion: Rules, Traces and Traps. This example needs only the type rules that determine its result.

3. For, while and do-while use the same control questions

Every loop can be read as four parts: initial state, condition, body and update. In for (int i = 1; i <= 3; i++), the values printed are exactly 1 2 3. The next check fails when i becomes 4, and the loop stops. Because i was declared in the header, it is then out of scope.

A while loop checks before its body:

java
int n = 3;
while (n > 0) {
    System.out.print(n + " ");
    n--;
}

It prints 3 2 1 and ends with n = 0. A do-while checks after its body. int k = 0; do { System.out.print(k); k++; } while (k < 0); prints 0 once and ends with k = 1 because the condition is checked after the body. The earlier Loops in Java Tutorial: for, while, do-while and Worked Examples explains loop forms and nested-loop traces. The remaining trace combines those controls with variable types and changing values.

4. Worked trace: variables, types and a loop in one program

Trace this program without trying to jump straight to the printed line:

java
int total = 3;
double factor = 1.5;

for (int i = 1; i <= 4; i++) {
    if (i % 2 == 0) {
        total += i;
    } else {
        total += 1;
    }
}

double score = total * factor;
System.out.println(total + " " + score);

Before the first iteration, total = 3. Now apply the condition, branch and update in order:

  • At i = 1, the condition is true. The odd branch adds 1, so total changes from 3 to 4.

  • At i = 2, the condition is true. The even branch adds 2, so total changes from 4 to 6.

  • At i = 3, the condition is true. The odd branch adds 1, so total changes from 6 to 7.

  • At i = 4, the condition is true. The even branch adds 4, so total changes from 7 to 11.

The update then makes i = 5. Since 5 <= 4 is false, the body is not entered again. Next, score = 11 * 1.5 = 16.5, so the exact output is 11 16.5. The variable total is still an int, factor is a double, and their multiplication produces a double. The loop variable i cannot be used after the loop.

Five-row Java loop trace table shows i values 1 through 5, branch operations, total changing from 3 to 11, and final score 16.5.

5. Five traps that make simple Java traces go wrong

  1. Integer division: double a = 5 / 2; stores 2.0, not 2.5, because Java completes the integer division first. double b = 5 / 2.0; stores 2.5 because one operand is a double.

  2. Off-by-one bounds: for (int i = 0; i <= 3; i++) runs four times, for 0, 1, 2, 3. Use i < 3 for exactly three iterations, 0, 1, 2.

  3. Scope: after for (int i = 0; i < 2; i++) {}, System.out.println(i); fails to compile. Declare i before the loop only if it genuinely needs wider scope.

  4. Missing update: while (n > 0) repeats forever if its body prints n but never changes it. Starting from n = 3, adding n--; makes the loop print 3 2 1 and terminate at 0.

  5. Assignment in a condition: with boolean ready = true;, if (ready = false) assigns false, so the branch is skipped. Use if (ready) when testing whether it is true, and always record the assignment's value change.

6. How exams and screening tests combine these basics

Practice tasks ask you to predict output, count iterations, identify a conversion result, find an out-of-scope variable or repair a non-terminating loop. A Java question set can test the same foundations without assuming that any official exam follows one fixed pattern.

Try two rapid checks. First, int s = 0; for (int i = 1; i <= 5; i += 2) s += i; visits 1, 3 and 5, so s = 1 + 3 + 5 = 9. Second, with int a = 7, b = 2;, a / b uses integer division and equals 3, while a / (double) b equals 3.5.

For either form, draw a tiny trace table before looking at answer choices. Write the iteration value, the condition result, the selected operation and the new variable value. This takes seconds and prevents most mental shortcuts.

7. The short version and a concrete next step

For every trace, identify each variable's type and scope, record its current value, then test the loop condition and update in order. As a ten-minute drill, change the worked bound to i <= 5: the added odd iteration takes total from 11 to 12, and score = 12 * 1.5 = 18.0. Then set factor to 2.0; with total = 12, score becomes 24.0.

Continue with the Complete Java course for a structured path, or use the Coding & Skills catalogue to choose a narrower next topic.