This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static block" Watch "static block" New topic
Author

static block

krussi rong
Ranch Hand

Joined: Jan 30, 2002
Posts: 62
Hi,
here is the question:
public class Q8
{
int i=20;
static
{
int i=10;
}
public static void main(String[] args)
{
Q8 a = new Q8();
System.out.println(a.i);
}
}
So why can delare the same variable in the
static block with the instance variable?
Does the static block's variable 's scope
only in the static block? if not how can access
the static block variable in the main method?
thanks
Krussi
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by krussi rong:
Hi,
here is the question:

So why can delare the same variable in the
static block with the instance variable?
Does the static block's variable 's scope
only in the static block? if not how can access
the static block variable in the main method?

The variable i, within the static block, has scope only within that block. In fact, you're hiding the instance member i with that local variable. There is no way to access that variable once you've reached main because, by that point, the variable has gone out of scope.
Corey


SCJP Tipline, etc.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: static block
 
Similar Threads
from mock exam qs.
Doubt in static...
static keyword over a block
Question on toString and Static
static block