• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Static initializer order

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is a question from the Whizlabs free trial for SJCP 1.4 exam:



I am confused as to why the answer is 3. The answer indicates that the values of x and y are set to zero. Why wouldn't x be set to 5?
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Take special note of the line in the static initializer:



See the "int" at the beginning of that line? Due to that, we don't assign 5 to the class variable, we create a new local variable and assign 5 to that. The class variable, Static.x is initialized to 0.

Then, to start the main method, we decrement x, taking it to -1.

When we invoke myMethod, we get this:



So, when the assignment is applied x is equal to 1 and y is set to 0.

Finally, back in the main method, we execute this line:



Hopefully, that helps you see why you get the result that you do.
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ahhh, such a small little word but makes all the difference in the world. Thanks.
 
Tick check! Okay, I guess that was just an itch. Oh wait! Just a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic