Syntax Quiz 2, Step 16

Assignment:

Write an assignment statement to set localVar to this value [i.e. the square root of instanceVar].

My solution:

localVar = Math.sqrt(this.instanceVar);
or
localVar = Math.sqrt(instanceVar);
(Again, the this. isn't required by Java, but I prefer it.)

Common mistakes:

Putting localVar on the right side of the equals sign, and Math.sqrt(this.instanceVar) on the left, e.g. Math.sqrt(this.instanceVar) = localVar;
The assignment statement in Java (and C, and C++, and Pascal, and many other languages) is not symmetrical: you must put the thing you want to change on the left, and the value you want to change it to on the right.
Putting a this. in front of localVar, e.g. this.localVar = Math.sqrt(this.instanceVar);
The code this.instanceVar refers to the instanceVar part of an object named this. But localVar isn't part of anything larger; it's just a variable used temporarily during this one method.
Omitting the semicolon at the end.
The assignment statement is a statement, along with variable-declaration statements and a number of other kinds of statements, all of which end in semicolons.

Stephen Bloch / sbloch@adelphi.edu