Static block

What are the contexts in which static block is used?
Plz..I dont need an answer like---Whenever anything need to be executed/initialised before main method, static block is used..
I need the contexts in which static block are used/would be helpful..
Regards,
Anees

A static block has nothing to do with the main method.
"static" means: associated with the class itself, rather than individual instances of the class. So a static block can be used to manipulate static variables, or perform other actions when the class is loaded.
For example, it could be used to fill a static collection of values:public static final Map<String, Country> countries = new HashMap<String, Country>();
static {
  countries.put("us", new Country("us", "United States of America");
  countries.put("ca", new Country("ca", "Canada");
  // etc...
}

Similar Messages

  • Help required in understanding of static blocks in java

    Hi ,
    Can some one help me in understanding the difference between static blocks in java....also what is the difference in declaring some static variables in a class and and declaring some variables in a static block? From an architecture viewpoint when should one use static blocks in Java?

    Static blocks are piece of code that can beexecuted
    before creating an instance of a class.static blocks are executed once, when the class
    itself is loaded by the JVM. They are not executed
    before creating each instance of a class.
    For example whatever you include in the mainn method will be
    executed without you having to create the instanceof
    the class using the new operator. So you can saythe
    main method is a static block.main is not a static initialisation block but a
    static method. a special case static method at that -
    it is only executed when the containing class is
    specified as a parameter to the JVM. (unless you
    specifcally call it elsewhere in code - but that
    would be bad form).
    in answer to the original post, static variables
    belong to the class. each instance of the class share
    the same static variables. Public static vars can be
    accessed by prefixing them with the class name. A
    static initialisation block can be used to
    initialise static variables. Variables declared
    within the static initialisation block exist only
    within the scope of the block.
    e.g.
    public class Foo {
    static Bar bar;        // static member variable
    // static initialisation block
    static {
    // variable declared in static block...
    String barInfo =
    arInfo = System.getParameter("barInfo");
    // ... used to initialise the static var
    bar = new Bar(barInfo);
    So is the only purpose of static initialization blocks is to initialize static variables? Does the initialization of static variables inside a static block make any difference in performance? If yes , then how ?

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

  • Foreach loop in static block won't compile

    When I try to compile this:public class TestEnum
      private static String[] numerals =
          {"einz", "zwei", "drei", "vier"};
      static
        for (String n : numerals)
          // doesn't matter what's in here
      public static void main(String[] args)
    }I get this exception:An exception has occurred in the compiler (1.4.2-beta).
    java.lang.NullPointerException
        at com.sun.tools.javac.comp.Lower.visitArrayForeachLoop(Lower.java:2269)
        at com.sun.tools.javac.comp.Lower.visitForeachLoop(Lower.java:2242)
        at com.sun.tools.javac.tree.Tree$ForeachLoop.accept(Tree.java:559)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.tree.TreeTranslator.translate(TreeTranslator.java:51)
        at com.sun.tools.javac.tree.TreeTranslator.visitBlock(TreeTranslator.java:131)
        at com.sun.tools.javac.tree.Tree$Block.accept(Tree.java:497)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.visitClassDef(Lower.java:1645)
        at com.sun.tools.javac.tree.Tree$ClassDef.accept(Tree.java:409)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1580)
        at com.sun.tools.javac.comp.Lower.translate(Lower.java:1594)
        at com.sun.tools.javac.comp.Lower.translateTopLevelClass(Lower.java:2438)
        at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:408)
        at com.sun.tools.javac.main.Main.compile(Main.java:523)
        at com.sun.tools.javac.Main.compile(Main.java:41)
        at com.sun.tools.javac.Main.main(Main.java:32)The same thing happens if I use foreach with a Collection instead an array. If I use an old-style for loop or Iterator in the static block, it compiles fine. I can also put the foreach loop in the main method, and it works. Is this a known bug?

    You guys rock. Thanks for finding this problem. I'll get it fixed.

  • Use of functions in static block

    Hello,
    I have this app containing a static {} block. The reason it's there is to 1) provide a splash screen 2) have input dialog to process input string and check if it's valid in order to load app or not.
    In pseudocode it's like this:
    1 - get input string with showInputDialog()
    2 - check for the input string validity (a valid string is with prefix A-, C- or S-)
    3 - if string is valid, load the app
    4 - if string is not valid, proceed to step 1.
    As you may already see, there is going to be a lot of code (with if-else statements) to check for A-, C- and S- prefixed because I am using indexOf() function which takes only one parameter.
    I am considering a way to somehow check recursively, but for this I think I'll need a function to call indexOf() with A-, C-, S- and assess validity for each case.
    My question is, is there a way in the static block to have a function? Or can somebody please recommend an efficient approach to checking a string validity with different possibilities inside a static block as in my case, to avoid lots of if-else statements?
    P.S. My apologies for initially posting this thread in wrong section.
    Thank you!
    Victor.

    DrClap wrote:
    What's a function? And why are you particularly concerned about doing those things in a static initializer as opposed to in some other place?Hi,
    Sorry, I'm still thinking c++. I meant method. Something like of the form:
    static
    boolean valid = false;
    while string is not valid
    stringfrominput = showInputDialog();   
    //determine if string is valid
    valid = checkvalid(stringfrominput)
    //if possible to have
    boolean checkvalid(stringfrominput)
    recursively process stringfrom input based on A-, S-, or C- prefixes
    return boolean value
    }I have a jar app. It is Windows-based and runs as a TrayIcon application. If I include this process when class is loaded, this means that the app will be loaded with all its features. But I need to make sure that the app's features will be loaded only if certain conditions are met.
    I am not sure how else to approach this requirement without using static {} block.
    Thank you,
    Victor.

  • Why do we use static block ????

    my question is that why do we use static block for certain statements and declarations ?? what advantage do they hold???
    Please help me........

    Here is an example:
    If you use a JDBC-driver, it's enough to write:
       String driverName = "package.MyDriver";
       Class.forName(driverName);In the class "MyDriver" there is a static block:
    public class MyDriver implements java.sql.Driver {
       static {
          MyDriver driver = new MyDriver();
          java.sql.DriverManager.registerDriver(driver);
    }

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Clarification regarding static blocks.

    I can understand from this about the static initialization block. I just need one clarification. What is the difference between the blocks with and without the 'static' keyword? For eg., the following code prints 'Hello'
    class ClassWithStaticBlock {
              System.out.println("Hello");
    public class StaticBlockTester {
         public static void main(String[] args) {
              new ClassWithStaticBlock();
    }If I modify the class ClassWithStaticBlock like given below, I receive the same output. So, what is the difference between the two?
    class ClassWithStaticBlock {
         static {
              System.out.println("Hello");
    }Thanks.

    The static block is only run upon loading of the class. Well, during the initialization phase of loading it, but it amounts to much the same thing. Non-static initiializers are run every time the class is instantiated. Try this
    class ClassWithInitializers {
      static {
       System.err.printlln("Loading class");
        System.err.println("Initializing");
      public static void main(String[] args) {
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
    }See any difference?

  • Exception handling in static block

    How to handle and exception raised in static block, pls answer

    Yeah, you are right, but I was just quoting the example on how to use it.
    Now, come to your problem,
    1. Static blocks are executed first time, when a class is loaded, i.e. when first reference of class is made.
    2. So, handle the situation there.
    E.g.
    You have test class:
    public class Test {
         static{
              try{
                   String s = null;
                   File f = new File(s);
              }catch(Throwable ne)
                   System.out.println("Eror");
                   throw new RuntimeException(); // Or use Error depends on your implementation
         public static void abc(){
              System.out.println("Hello");
    Now,
    calling it from another class:
    public class Test1 {
         public static void main(String[] args) {
              try{
              Test.abc(); *// This is the first instance where class for Test will be load and hence the static block will be executed*
              }catch(Throwable th) // Or catch Error
                   th.printStackTrace(); // Do the handling
              System.out.println("Done");
    This is a standard practice. From static block, instead of throwing Error exception, use some of your inherited class from Error. (i.e. create a exception framework inside your application)
    Hope this explains my point.

  • Error handling in static block

    Hello All,
    I have the following code
    static{
    abc();
    private static void abc() throws Exception{
    how do I throw error in static block because if I write
    static {
    abc() throws Exception;
    it gives error during compilation.
    How do I handle it.
    Sachin

    This is my code ...
    import java.io.FileInputStream;
    import java.io.*;
    import java.util.Properties;
    * @author sachin
    * This class is used setting the configurations
    public class Config{
         static String files_incoming;
         static String files_outgoing;
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
                   LoggerCitiUtil.debug("Error in static block");               
         public static void configurations() throws ICMSException{
              Properties prop = new Properties();
              try{
                   Properties property = System.getProperties();
                   String systemPath = property.getProperty("MAIN_BASE_PATH");
              prop.load(new FileInputStream( systemPath + "bin/scp.ini"));
              }catch(IOException e){                 
                   LoggerCitiUtil.debug("File not loaded in Config class");               
              try{
    files_incoming=prop.getProperty("files_incoming").trim();;
    files_outgoing=prop.getProperty("files_outgoing").trim();;                                   
              }catch(Exception e){
                   LoggerCitiUtil.debug("Error in Config class");
                   e.printStackTrace();
    In the static block I want to throw new ICMSException(e);
    When I write this :
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
    throw new ICMSException(e);
                   LoggerCitiUtil.debug("Error in static block");               
    But it gives unhandled Exception during compile time.
    Can anyone help me out ?.

  • Exception in static block + re-instantiating

    Hello All,
    I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
    But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
    But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
    Regards
    Jonas

    It's part of the VM Specification.
    See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
    The first time,
    10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
    5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

  • Problem in static block execution

    Hi all
    i have a class which has a static block and a static method.For the first time i call the static method in the class its strange that its excuting a part of the static block and entering the method later and agian turning back to static block.
    but for the secon time when i call the static method in that class its fine that static block is not executed..
    here is the code of the class which contains static block and static method
    public class LogServices
    private static String propFilename="plas.properties";
    private static String file="vdvd";
    static
    System.out.println("Inside static block");
    try
    System.out.println("Inside static block of Plasma Log Services ");
              file=PropertyProvider.getProperty(propFilename,"Log4jprops"); // here i am calling another method in another class to get some string from properties
    System.out.println("\n File is ********************************** "+file);
    catch(Exception e)
    System.out.println("Exception encountered the following Exception ["+e.getMessage()+"]");
              System.out.println("Finished static block");
    public static Logger initLog()
    Logger logger=Logger.getLogger(PlasmaLogServices.class);
    System.out.println("File in method is:"+file);
    return logger;
    and in my main program i am calling this
    LogServices.initLog(); and the output i observed on the screen is
    Inside static block
    Inside static block of Plasma Log Services
    File in method is:vdvd
    File is ********************************** log.properties
    Finished static block
    if u look at the output after " Inside static block of Plasma Log Services" (part of static block) its enetering method where " File in method is:vdvd" is printed .
    After some debugging i came to know that if i remove the line
    file=PropertyProvider.getProperty(propFilename,"Log4jprops"); and replace it by file="log.properties";(mean hardcoded) then the static block executes and later that method executes.
    can any one pls help me in this regard???

    The first time you instantiate a class
    LogServices, it's static block is being
    executed.
    After you've instantiated the class, you call its
    static method.
    If you call the static method again, the
    LogServices have their static block already
    executed, so it won't be executed again.
    I think that the execution of static block and static
    method is not mixed, as you thought. I think it is
    rather a logging issue. Most loggers do not guarantee
    that logging-messages are output in correct order.
    Regards, TomHello sir
    tahnks for ur reply and i got that .the problem was in the propertyprovider class i had a static variable logger =PlasmaLogservices.initLog() ; and hence after that it was by passing to that static method and coming back again .
    thanks for looking in to this

  • Static block in java

    Suppose I have a class that has a static block in it
    public abstract class A {
        static {
        public A(){
        public void doSomething(){
    }And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class C
    public class B extends A {
        public B(){
    public class C extends A {
        public C(){
    }

    And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class CA static block (or static initializer) is executed only once per class, when the class is initialized. The fact that several other classes subclass the superclass does not imply it has to be reinitialized.

  • Regarding static block

    Hi,
    I need to get two properties from the properties file and i will use these properties across the application,How can i write the util class which get the two properties and i can use acrross the application.
    Can i use the staic block in the util class ?
    Pls suggest me.
    Thanks
    crr

    I would use a util class to lazily load the properties file. You will need to handle certain IO exceptions when loading props, which is too much for a static block to handle properly. For example,
    public synchronized Properties getProps() {
        if(this.props == null) }
            loadProps();
        return this.props;
    }-cheng

  • Weird Static Block Behaviour

    Hi There,
    I have a class to provide constants that is initialised using a static block...
    public final class ConstantNames {
        public static final String NAME1= "Name 1",
                NAME2= "Name 2",
                NAME3= "Name 3",
                NAME4= "Name 4",
                NAME5= "Name 5",
                NAME6= "Name 6",
                NAME7= "Name 7";
        private static final Set<String> VALUES;
        static {
            VALUES = CollectionsUtils.makeSet(NAME1, NAME2, NAME3, NAME4, NAME5, NAME6, NAME7);
        public static Set<String> values() {
            return VALUES;
         * Prevents construction.
        private ConstantNames () {
    }It works as expected in my local environment (Win XP/JDK 1.5) but in the production environment (Linux/JDK 1.5) It 'loses' NAME7 such that...
    ConstantNames.values().contains("Name 7")...returns false (its true for "Name 1" .. "Name 6")
    Can anyone shed any light on this for me - thanks

    On WinXP, its fine - you can add re-arrange doesn't make any difference. Its harder for me to make quick tests/changes in the Linux production environment. The latest change I'm releasing has done away with the static block so the Set is defined as...
    private static final Set<String> VALUES = CollectionsUtils.makeSet(NAME1, NAME2, NAME3, NAME4, NAME5, NAME6, NAME7);
    ...hoping (blindly) that this will make a difference. I'll see if I can do some more testing in the 'problem' environment without having to go through the whole release procedure.
    Thanks

  • Construct Derived Class in Static Block

    We've been having intermittent thread deadlock problems after migrating a stable system to Linux.
    One locked section we noticed occurred about 1 in 5 times, right at startup. The code looked fishy from the beginning, but I thought others could confirm whether it could be the cause of our problems.
    The code block constructs a derived class from a static block in the parent. Is it a recipe for failure? If so, why only intermittently and why not in Windows?

    The code block constructs a derived class from a
    static block in the parent.I don't understand that sentence. You have a block of code. It calls a constructor? It calls a constructor for a class that's derived from ... a static block? What do you mean?
    Is it a recipe for
    failure? If so, why only intermittently and why not
    in Windows?Intermittent failure is the nature of thread problems. Windows and Linux can have very different underlying implementations of threads.
    Show us some of the code and the failure mode.

Maybe you are looking for