• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Static initialization block is for program code only?

 
Greenhorn
Posts: 1
Android Debian Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static initialization block is for program code only? One would think you could declare static variables inside a static initialization block (int myNum = -1;) and have it be static or global.

I haven't encountered it until today.
 
Saloon Keeper
Posts: 6049
58
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, a static initializer block could declare variables that are local to that block. How would they be differentiated from the declaration of an member variable?
 
Marshal
Posts: 65108
247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

What do you mean about working for program code only? Don't declare global variables; only declare constants global. And make sure any reference types are immutable.
 
Rancher
Posts: 3305
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Walter Williams wrote:One would think you could declare static variables inside a static initialization block (int myNum = -1;) and have it be static or global.



While the creators of Java could have made it work that way, they didn't.  If you declare a variable in a code block or method, it's only going to be local to that block or method.  In order to have a wider scope, it would need to be outside a block, but inside a class - either static or non-static.

A static initialization block is good for doing something upon class loading.  It isn't useful for declaring something.
 
Saloon Keeper
Posts: 3415
149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recently used it to define a static Comparator. The code I used:

So, c1 and c2 are local to the static block, and comp is not.

Do we need this static block? Hmm.. where else would you define it? The reason I do this is to make a very easy compareTo method (since my class implements Comparable<A>). That method is then simply:

I find that very comfortable.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!