• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt on order of execution

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to all...that was useful
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic