[Solved-2 Solutions] “Cannot find symbol” compilation error
Error Description:
- How to fix the error “Cannot find symbol” compilation error”?
Solution 1:
for (int i = 1; i < 10; i++) {
for (j = 1; j < 10; j++) {
...
}
}
click below button to copy the code. By - Java tutorial - team
- Suppose that the compiler says "Cannot find symbol" for j.
- There are many ways you could "fix" that:
- You could change the inner
fortofor (int j = 1; j < 10; j++)- probably correct. - You could add a declaration for
jbefore the innerforloop, or the outerforloop - possibly correct. - You could change
jtoiin the innerforloop - probably wrong! and so on.
- The point is that you need to understand what your code is trying to do in order to find the right fix.
Solution 2:
Consider this code:
if(somethingIsTrue()) {
String message = "Everything is fine";
} else {
String message = "We have an error";
}
System.out.println(message);
click below button to copy the code. By - Java tutorial - team
- Because neither of the variables named
messageis visible outside of their respective scope - which would be the surrounding brackets{}in this case. - You might say: "But a variable named message is defined either way - so message is defined after the
if".
- Java has no
free()ordeleteoperators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).
if(somethingIsTrue()) {
String message = "Everything is fine";
System.out.println(message);
} else {
String message = "We have an error";
System.out.println(message);
}
click below button to copy the code. By - Java tutorial - team
- "Oh, there's duplicated code, let's pull that common line out" -> and there it is.
- The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:
String message = "We have an error";
if(somethingIsTrue()) {
message = "Everything is fine";
}
System.out.println(message);