File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on order of execution

 
Sugantha Jeevankumar
Ranch Hand
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Amirr Rafique
Ranch Hand
Posts: 324
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Praveen Javvaji
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all...that was useful
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic