Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can't I access the class variable?

 
Maduranga Liyanage
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am a little baffled here.
I wanted to check about multiple thread with the same name so I code the following:





Everything work fine except for the final 'println' (after the for loop).
Gives me a compiler error:

ThreadTesterClass.java:17: cannot find symbol
symbol : variable T
location: class ThreadTesterClass
System.out.println(T.value);
^


I am wondering why it cannot see the object 'T', while inside the for loop it works fine.

Thank you.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You declare T inside the for loop, therefore the scope of T is inside the for loop. Your print statement is outside the for loop, so the compiler doesn't know what T is.
 
Maduranga Liyanage
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh..Thanks Neal..
Didn't know that.. for loop is also like a method?
The variables declared inside the loop also have method scope?

Thanks mate.. strange how I missed that...
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The scope of a variable is from the point it is declared, to the closing } that matches the first unmatched opening { preceeding the declaration. These opening and closing braces can be around method/constructor declarations, for/while loops, if clauses or even just a block of code
[ July 30, 2008: Message edited by: Joanne Neal ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic