Jump to content

Static Initializers

- - - - -

  • Please log in to reply
4 replies to this topic

#1
Generic

Generic

    Newbie

  • Members
  • PipPip
  • 26 posts

public class Main {

    private static Map<String, Integer> myMap = new HashMap<String, Integer>();

    static { // Static things load from top to bottom so putting the map below this code block results in an illegal forward reference

        myMap.put("1", 1);

        myMap.put("2", 2);

        myMap.put("3", 3);

        myMap.put("4", 4);

    }


    public static void main(String[] args) {

        for (Entry<String, Integer> entry : myMap.entrySet()) {

            System.out.println(entry.getKey()+ ": " + entry.getValue());

        }

    }

}

The static block gets called in the order its placed. With this if you're working with static things you can put initialization code into a static initializer instead of having a method that needs to be called before things are used inside of the class.

#2
Hurricane

Hurricane

    Newbie

  • Members
  • PipPip
  • 20 posts
Thank you, that was really useful. I believe I will a good use to it.

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I didn't even knew that.
The time that I have a need for such a static block has yet to come but thanks for sharing :)

#4
Hurricane

Hurricane

    Newbie

  • Members
  • PipPip
  • 20 posts
^
I've been programming for a while now, and I had the need for a static block, but whenever I needed to use it, I just put the code instead the first lines of each constructor. Kinda silly and code reuse, but it worked properly. :D

#5
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
I've found the static block to be good for complex initializations of class-wide static-finals. Also, if you get into loading classes dynamically, they can be really useful for some particularly interesting tricks. :) For example, the JDBC API requires that each implementor of a JDBC frontend must register their driver to the JDBC DriverManager. This must be done when the frontend class is loaded into the JRE (IE, using a static block, you must register the driver using DriverManager.registerDriver()).
Wow I changed my sig!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users