Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When will we go for static block...?

 
Naveen Raja
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I know that static block can be defined in a class,but when we have to go for it and how compiler treats it..?

Thanks in Advance

Naveen.
 
Nikhil Goel
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static blocks are intialized the first thing even way before constructors.

Usage can be to intialize connection pools etc . Normall all other utility stuff can be taken care in static blocks
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JDBC driver, for example, use static blocks to register themselves to the DriverManager. That's why loading a JDBC driver by Class.forName initializes it.

Another use is to initialize complex static variables, such as Collections etc.

They shouldn't be used too often, though - most often there are better (more flexible) alternatives to static blocks.
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just wanted to add that a static block is executed when the class is first loaded & initialized for use.
The JVM spec has more accurate definitions about this, but usually you'll notice that a class is loaded & initialized when you first use it - e.g. when you first try to create an instance, or use some static methods/variables.

A classic example:
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to Naveen Question, what all resolutions happen at compile time and what all are left for run time.

can someone pls point me to appropriate resource

thanks ahead,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic