aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on order of execution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on order of execution" Watch "Doubt on order of execution" New topic
Author

Doubt on order of execution

Sugantha Jeevankumar
Ranch Hand

Joined: Jun 06, 2007
Posts: 93
I understand that static blocks run first (as per the order in which they are defined) followed by an objects superclass constructors,init blocks and the current constructor...But what gets executed first.. static variable definition or static block definition...I ran into a mock question like this...



I thought since x is defined twice there'll be a compiler error..But the explanation goes like this..."The execution of the static block will have no effect as a new variable x is created.Please help me with the order of execution.Thanks in advance


SCJP 5.0
Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324
The x variable in static block is local to that block so by the time the line static int x,y; is executed the static block x will be out of scope.


"Know where to find the solution and how to use it - that's the secret of success."
Praveen Javvaji
Greenhorn

Joined: Dec 18, 2007
Posts: 4
Hi Sugantha,

Your understanding of order of execution is correct for static blocks, init blocks and constuctors.

Since the x in static block is belonging to that block only, i.e., local to that block. So no compilation error occurs with conflict to static int x.

Next you asked for the explanation for getting the output. Here it follows:
static variables x and y are initialized to 0 by default.

In the main method x-- makes it -1.
Then in myMethod x is post incremented so the equation for
y=x++ + ++x will be y=(-1)+(0+1) here x is -1, x++ will be 0 and then ++x will be 1, so y will be 0.

Thereafter in SOP the result printed will be 3.

Sugantha Jeevankumar
Ranch Hand

Joined: Jun 06, 2007
Posts: 93
Thanks to all...that was useful
 
 
subject: Doubt on order of execution