File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes When to use Static initial block? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use Static initial block?" Watch "When to use Static initial block?" New topic
Author

When to use Static initial block?

Rakesh shankar
Greenhorn

Joined: Nov 12, 2010
Posts: 14
Hi,

Can we use constructor to initialize static members of a class.
If this is possible then what is the use of static initial block.

Can anyone explain me in which scenario we go for static initial block??

Thanks in advance..
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Rakesh Ss wrote:... Can we use constructor to initialize static members of a class.
If this is possible then what is the use of static initial block...

A constructor is only called when an instance is being created. So for static (class) members to be properly initialized, a constructor will not work, and a static block might be required instead.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

Except if the static fields are only used through instance methods, then you can do lazy initializing through the constructor.
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
You're asking about a "static initialization block," right?


Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
Static blocks -are static ,they run when class is loaded and not associated with any instances /objects of class or constructor(constructor constructs an object)


Stephen -

"Except if the static fields are only used through instance methods, then you can do lazy initializing through the constructor."

I am really interested in the exceptional case that you mentioned.Can you please provide some examples to explain better.

Thanks.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17


Here is such an example. Let's say Expensive objects are very expensive to create. You don't want to create them until you really have to. If the Expensive object is only used by instance methods, like plus(), you can avoid creating one until the first instance of Test is created. This way, if a program only needs the help() method, it can avoid creating a Test (and thus an Expensive) altogether.

This is a rare situation, but it's just an example.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use Static initial block?