• 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

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
 
Well behaved women rarely make history - Eleanor Roosevelt. tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic