[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:
      1. You could change the inner for to for (int j = 1; j < 10; j++) - probably correct.
      2. You could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
      3. You could change j to i in the inner for loop - 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 message is 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() or delete operators, 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);
      
      click below button to copy the code. By - Java tutorial - team

      Related Searches to “Cannot find symbol” compilation error