ExpressionAssigns
DRAFT

Misconception:

Using a variable in an expression, such as x+1, also updates the value of the variable (x in this case) at the end of the evaluation, even without an assignment.

Incorrect

An expression that reads a variable also updates its value after the evaluation

Correct

A variable is only written using an assignment

Correction
Here is what's right.

Students might mistakenly believe that reading from a variable score within an expression score + 10 also updates the value of the variable (score in this case).

For example, they might believe that the following code outputs the three numbers: 4, 14, and 14.

int score = 4;
System.out.println(score);
System.out.println(score + 10);
System.out.println(score);

This is wrong. The above code prints the numbers 4, 14, and 4.

To mutate a variable, one needs to use an assignment like score = 14 or score += 10.

Note that in Java, assignments are expressions. Thus, the following code is possible:

int score = 4;
System.out.println(score);
System.out.println(score += 10);
System.out.println(score);

This would print the numbers 4, 14, and 14.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.