Skip to main content

Section 9.3 Forgetting to declare your variables

In Python, you can use a variable without declaring it first, but in Java, you must declare all variables before using them. Listing 9.3.1 shows If you try to use a variable that has not been declared, the Java compiler will give you an error message like this:
Listing 9.3.1.
The ’cannot find symbol’ error for the variable count on line 6 indicates that count was used before it was declared within the Histo class. In Java, all variables must be explicitly declared with a data type (e.g., int, String, ArrayList<Integer>) before they can be assigned a value or referenced in any way. The arrow in the error message points to where the undeclared variable count was first encountered. To resolve this, count needs to be declared with its appropriate type (e.g., ArrayList<Integer> count;) before any attempt to initialize or use it.

Checkpoint 9.3.2.

Based on Listing 9.3.1, select all of the statements that are true about declaring variables in Java.
  • Every variable must be declared with a data type before it is used.
  • Correct! Java requires a variable to be declared with its type before it can be assigned or referenced.
  • The "cannot find symbol" error happens because count was used before being declared.
  • Correct! That error means the compiler reached a variable it has no declaration for.
  • Writing ArrayList<Integer> count; before using count would fix the "cannot find symbol" error.
  • Correct! Declaring count with its type resolves the error.
  • Java lets you use a variable without declaring it first, just like Python.
  • Incorrect. Unlike Python, Java requires all variables to be declared before use.
  • The error can be fixed by adding an import statement.
  • Incorrect. The import is already present; the problem is the missing variable declaration, not a missing import.
You have attempted of activities on this page.