Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static blocks vs static items

 
Adam Price
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any difference between


and



It doesn't seem to matter in the simple code I am writing for my assignment, and I can't think of why it would, but could it ever?
 
Adam Price
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK - I just figured out one way it would make a difference - If I needed to access hashKeys or hashValues anywhere else, I would need to use the second form. I don't quite understand why, but I am mulling on it....
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static {} is a static initializer. It executes when the class is first loaded. Within that block you can declare local variables, which is what you're doing in the first form. As soon as execution leaves the block those variables are out of scope. The second form is one where you are declaring static member variables.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words, a static initializer is very much like a method that gets executed when the class is loaded.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic