Syntax Quiz 2, Step 2
Assignment:
Write a variable declaration for an instance variable
named instanceVar
, of a type suitable to hold an integer.
My solution:
int instanceVar;
or
private int instanceVar;
(the private
is optional.)
Common mistakes:
- Not specifying the type.
- Every variable used in a Java program must be declared, with
a specific type, before it is used. The way to tell Java
you're declaring a new variable is to write a type name, a space, and
then the name of the new variable.
- Putting quotation marks around the variable name.
- Variable names cannot contain quotation marks. Quotation marks,
in Java (and most other languages) indicate a literal string,
i.e. a specific sequence of characters, typically to be printed out
exactly as they appear between the quotation marks. A variable, by
contrast, contains a value: for example, an int variable
named
instanceVar
might contain the integer value 12, which
has nothing to do with the characters of the variable's name.
- Putting parentheses after the variable name.
- There are no parentheses in a variable declaration; you're confusing it
with a method header.
Last modified:
Stephen Bloch / sbloch@adelphi.edu