Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable out of scope, Error: cannot find symbol

Tags:

java

scope

static

the Error is:

cannot find symbol System.out.println("value of count" + count);

Symbol:

variable count

Location:

class synchronize

I declared count variable static so doesn't that mean every class can access it?

class a extends Thread 

{

public static int count=0;

public void run()

 {

   for(int i=1;i<=100;i++){

   count++;
    }
  }
}

class b extends Thread {

public void run(){

  for(int i=1;i<=100;i++){

  count++;
  }
 }
}

class synchronize {

public static void main(String args[]) {

  a obj =new a();

  b obj1=new b();

  obj.start();

  obj1.start();

  System.out.println("value of count "+count) ;

 }
}
like image 273
user187744 Avatar asked Dec 05 '25 17:12

user187744


2 Answers

the count variable is declared as a member of the a class.

So if you change:

System.out.println("value of count "+count);

To:

System.out.println("value of count " + a.count);

So that you are accessing the count variable as a member of the a class, then your synchornize class should be able to 'see' the count variable.

Also, you may want to use the a.count inside of class b as well:

class b extends Thread {

    public void run(){

      for(int i=1;i<=100;i++){

          a.count++;
       }
    }
}
like image 148
Blake Yarbrough Avatar answered Dec 08 '25 06:12

Blake Yarbrough


Static variables have a single value for all instances of a class.

You have to access static variables by class name

instead of this

System.out.println("value of count "+count) ;

use this

System.out.println("value of count "+a.count) ;
like image 20
King Avatar answered Dec 08 '25 07:12

King



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!