user3503297
user3503297

Reputation: 59

java tells that can not find symbol

I am studying core Java myself. I wrote a Java program, and I got one error:

...cannot find symbol "refc"

but it is already declared as object reference... Can anyone explain that?

import java.io.*;

class contactmain {
    int count = 0;
    int[] a = new int[5];

    contactmain() {
        System.out.println("a");
        a[count] = count+1;
        count++;
    }
}

class contact {

    public static void main(String args[]) { 
        int y = 0;
        int i = 0;
        while (i<10) {
            contactmain refc = new contactmain();//create the instance of that class
            i++;
        }
        System.out.println(refc.a[i]);
    }
}

In the last statement, I got an error {refc.a[i]} that it cannot find symbol. Please, help me.

Upvotes: 0

Views: 70

Answers (3)

Endrik
Endrik

Reputation: 2258

The problem is that you are declaring contactmain refc inside a block, which in this case is a while block statement. This means that this reference will be avaiable for use only inside the scope of this block (because this blocks have their own stack of memory, everything defined inside them can be used only there) So you have

while(i<10)
     {
        contactmain refc=new contactmain();
        i++;
      }

You can use System.out.println(refc.a[i]); only inside it. If you which to utilize this object reference outside the block, you should declare it before entering the block. For example:

contact main refc = null;
while(i<10)
         {
            refc=new contactmain();
            i++;
          }
System.out.println(refc.a[i]);

NOTE: Using lower case for naming is a bad practice. You should go with Camel-Case. Please refere to: Variable scope | Naming conventions

Upvotes: 1

Marco Acierno
Marco Acierno

Reputation: 14847

Because refc scope is limited inside the while.

To let it works, you could move your System.out.println(refc.a[i]); inside the while so the compiler will know the existence of refc

What is a "variable scope"?

Variable scope refers to the accessibility of a variable.

The rule 1 is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined.

Upvotes: 1

Pradeep Simha
Pradeep Simha

Reputation: 18133

Scope matters, you're declaring variable inside a while(..){ } and trying to access outside of the loop, change the code to:

while(i<10)
{
   contactmain refc=new contactmain();
   i++;
   System.out.println(refc.a[i]);
}

Upvotes: 4

Related Questions