wood burning stoves 2.0*
The moose likes Java in General and the fly likes Static block and static variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static block and static variable" Watch "Static block and static variable" New topic
Author

Static block and static variable

Dipti Mishra
Greenhorn

Joined: Jan 24, 2006
Posts: 22
Hi,
Can anybody clearly explain me that what is executed first? A Static block, a static method or static variables? What is sequence of execution of these following lines?

public class Static
{
static
{
int x = 5;
}

static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}

public static void myMethod()
{
y = x++ + ++x;
}
}

What will be the output? If you move the statis block below the static variable decalaration, why the output remains same.....

Please reply as soon as possible.

Dipti
Naveen Raja
Greenhorn

Joined: Jul 28, 2006
Posts: 10
Hi,

As for i understood, the var i defined in the static block is no way affecting the output..because...its scope is confined to that block...
So the output will be 3

And if you define static block something like below.

static int x,y;
static
{
x = 5;
}
Output will be 23

Here order matters...if you interchange the stmts, you will get compilation error " illegal forward reference"...

So if static methods are initializing any of the static var then order matters..

That is what my understanding...
 
Don't get me started about those stupid light bulbs.
 
subject: Static block and static variable