aspose file tools*
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 Java 8 in Action this week in the Java 8 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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static block
 
Similar Threads
Doubt in static...
from mock exam qs.
Question on toString and Static
static block
static keyword over a block