Syntax Quiz 2, Step 13

Assignment:

Write an assignment statement to set instanceVar to this value.

My solution:

You've already written the expression

theParameter.length()
To assign a variable to this value, write
this.instanceVar = theParameter.length();
or
instanceVar = theParameter.length();
(The this. isn't required by Java, but I think it helps to explain what's going on. instanceVar has no independent existence except as part of a QuizClass object. Since this is a QuizClass object, this.instanceVar is really the complete reference.)

Common mistakes:

Omitting the equals sign
The equals sign is how Java knows that this is an assignment statement, i.e. you're changing one variable to match another expression.
Reversing the positions of instanceVar and theParameter.length().
The assignment statement in Java (and C and C++ and Basic) looks superficially like an equation, but it actually has a very different meaning: the thing on the left side of the equals sign is changed to match the thing on the right side. So if you write
theParameter.length() = this.instanceVar;
you're trying to change the length of theParameter, rather than copying that length into another variable.
Omitting the semicolon.
The assignment statement is a statement, and therefore ends with a semicolon.
Writing a double-equals sign, as in this.instanceVar == theParameter.length();
The double-equals sign in Java (and C and C++) asks whether two things are the same. The assignment at hand is to make them the same. This error is particularly insidious because it's actually legal Java -- it won't produce a compiler error message -- but neither will it do anything.

Stephen Bloch / sbloch@adelphi.edu