Instance initializer and static initializer blocks

Hi guys,
I read about the above mentioned in the JLS and also in a book before, but I still don't quite understand, what is the use of these. I sort of have a rough idea, but not exactly. I mean, what is the purpose of the instance initializer and static initializer blocks, how can it be useful? I understand I can execute pieces of code that will initialize instance and static variables accordingly, but how is it different then to using a constructor to initialize these fields? Are these pieces of code executed before any constructor is executed, or when otherwise?
Sorry for my noob, I'm learning.
PR.

Static initializers are useful for initializing a class when the initialization is more complex than simply setting a single variable, or when that initialization can throw a checked exception.
public class Foo {
  private static final Bar bar;
  static {
    try {
      bar = new Bar();
      bar.doSomeInitializationStuff();
    catch (SomeCheckedExceptionThatBarThrows e) {
      throw new ExceptionInInitializerError(e);
}Here we could not do the two-step new Bar() + doSomeInit() stuff in the line where we declare the bar variable. Additionally, assuming that one or both of those can throw a checked exception, we could not do that on the declaration line; we need the static initializer to wrap that in the appropriate unchecked exception.
This allows us to do more complex class initialization when the class is loaded than we could do with a simple variable initialization.
Instance initializers are useful if you want to perform the same steps in every constructor and don't want to have to repeat the code in each constructor. Instance initializers are executed as the first step of each constructor (or maybe it's after any super() calls, I forget).

Similar Messages

  • Help required on java.lang.StackOverFlowError and static initializer

    I wanted to create an instance of a class that contains another instance of the same class. So I wrote:
    class A {
         A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }During execution I got java.lang.StackOverFlowError. But if I put a static initializer, it works fine. Here is the code using static initializer.
    class A {
         static{
              A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }Could anyone please help me to understand the logic why "java.lang.StackOverFlowError" is happening here and how the same program runs fine by putting a static initializer ?
    Regards,
    Shambhu

    Could anyone please help me to understand the logic
    why "java.lang.StackOverFlowError" is happening hereWhen you instantiate an A object with A y = new A () then A z = new A () also gets executed inside the A class, which in it's turn executes A z = new A () again, and again, and again...
    and how the same program runs fine by putting a
    static initializer ?Because the static block gets executed only once.
    The use of class- and instance variables is explained in more detail here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

  • JSP behavior - static initializer and jspInit

    In a recent discussion, the concept of using a static intializer in a JSP came up. The situtation was that someone had a series of Strings used in a single JSP and they wanted to #1, define these strings in the JSP itself (vs in web.xml or a resource file, which while preferable, was not really an item of discussion) and #2 wanted indexed access to the Strings (such as via a Map).
    My thought was to declare the Map variable as static final in the JSP and then initialize it in a static initializer block with Map.put operations. Both the declaration of the Map and the static initializer block would be declared in a <%! %> declaration tag block. (The thought behind the static initialization - vs overriding jspInit - being that if multiple instances of the JSP were to be created, we wouldn't want to keep put'ing values into the Map for each new instance of the JSP.)
    I built the following test scenario:
    <<untitled3.jsp source>>
    <%@ page import="java.util.*" %>
    <%!
    static final Map m = new HashMap();
    static int staticCount = 0;
    static int jspInitCount = 0;
    static {
    System.out.println("static initializer called");
    staticCount++;
    m.put("staticCount"+staticCount, "static# " + staticCount);
         public void jspInit() {
              super.jspInit();
    jspInitCount++;
    m.put("jspInitCount"+jspInitCount, "jspInit# " + jspInitCount);
    System.out.println("overriden jspInit called:" + this);
    %>
    Map values:<br>
    <%
    Collection values = m.values();
    Iterator i = values.iterator();
    while (i.hasNext()) {
    out.println(i.next().toString() + "<br>");
    %>
    Test
    <<end of untitled3.jsp source>>
    with the following web.xml entries:
    <servlet>
    <servlet-name>JSPServlet1</servlet-name>
    <jsp-file>untitled3.jsp</jsp-file>
    </servlet>
    <servlet>
    <servlet-name>JSPServlet2</servlet-name>
    <jsp-file>untitled3.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
    <servlet-name>JSPServlet1</servlet-name>
    <url-pattern>/jsp1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>JSPServlet1</servlet-name>
    <url-pattern>/jsp2</url-pattern>
    </servlet-mapping>
    I open a browser and request untitled3.jsp, I get the following output in the browser:
    Map values:
    static# 1
    jspInit# 1
    Test
    with the following output to my JDeveloper (9.0.3.1) log window:
    static initializer called
    overriden jspInit called:_untitled3@61
    I then request /jsp1 and get the following output in the browser:
    Map values:
    static# 1
    jspInit# 2
    jspInit# 1
    Test
    with the following output to my log window:
    overriden jspInit called:_untitled3@63
    Subsequent calls to /jsp1, /jsp2 or untitled3.jsp result in that same last output in the browser and no further output in the log window (ie, no further calls to the static initializer or jspInit method)
    So, it appears that jspInit is being called once for the unmapped JSP request and one more time, the first time one of the web.xml-mapped JSP instances is requested. (I'd have thought that it would be called once for the /jsp1 request and once for the /jsp2 request...), but the static initializer is being called only once as expected.
    Is this the correct behavior for the jspInit method? (ie, being called once for the unmapped request and once for the first mapped request?)
    Also, if OC4J is used in a clustered/balanced configuration, is it possible that I'd end up with additional instances of my JSP in one or more JVMs?
    Thanks!
    Jim Stoll

    You could scope such info to the application scope - some info is provided here: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html
    "application - You can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean."

  • Initializing array elements on a static initialization block

    Hello,
    I have this class:
    class Foo{
        public static Wing[] flights = new Wing[20]; //initialize with null Wing references
        static { //static initialization block - begin
            for(Wing w : flights){ //for each Wing slot on the array,
                w = new Wing();      //create a Wing object and refer to it
            } // static init block - endThe code above creates a Wing array, and the static init block should create 20 Wing objects on the array slots, but the objects are lost when I try to use it in the main method on the same class Foo:
        public static void main(String[] args){
             System.out.println(flights[3].name); //will throw NullPointerException -> Array elements have not been initialized  
        }How is that possible? The init code for(Wing w : flights) looks like has created copies of the objects, and not just references to the same object. If I change the static init block to the "old-fashioned for loop"
    for (int i=0; i < flights.length; i++){
    flights[i] = new Wing();then it works.
    But I think that the problem is not on the kind of for loop itself, because if I use same static initialization statement, with for (Wing w : flights) on the main method, instead of in a separate init block, the array gets populated with solid objects.
    Any ideas of what I am doing wrong?
    Java version: 5.0

    I think I got it. I am reseting the reference to point to a new Object in the heap instead of the array slot. :-P

  • Static initializer block

    use of static initializer block

    Going directly to the point aren't you?
    A ststic initializer block is used, well, to initializes static variable! It is called when the class is loaded.
    It is use like this.
    public MyClass {
       static {
          private int foo = 38;
       public static int getFoo() {
          return foo;
    }

  • [svn:osmf:] 15220: Fix static initialization order in OSMFPlayer, so that the Log doesn't create TraceLoggers and DebugLoggers.

    Revision: 15220
    Revision: 15220
    Author:   [email protected]
    Date:     2010-04-05 10:29:52 -0700 (Mon, 05 Apr 2010)
    Log Message:
    Fix static initialization order in OSMFPlayer, so that the Log doesn't create TraceLoggers and DebugLoggers.
    Modified Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/OSMFPlayer.as

    shak wrote:
    I've followed the first method with the mpd daemon and everything worked fine .
    THanks for all your help everyone !
    The add of MPD : ALL to hosts.allow seems to solved it .
    Thanks again!
    Nice.
    Please mark threads as [SOLVED] when they are. You can do so by editing the opening post.

  • APEX equivalent of Java Static Initialization Block

    Is there a APEX equivalent of Java static init block (i.e. execute once at class load time)? My use case is that I need to load some configuration values to an environment (i.e. APEX Workspace) specific variables and don't want to do per user session since the values remain the same for all user sessions. I believe SYS_CONTEXT is tied to user session and would not be useful for my usecase. Any advise would be appreciated.

    Hello,
    You should check the concept of User Preferences and see if it can help you:
    http://docs.oracle.com/cd/E23903_01/doc/doc.41/e21678/aadm_mg_sessions.htm#BABHFEFD
    Regards,
    Arie.
    &diams; Please remember to mark appropriate posts as correct/helpful. For the long run, it will benefit us all.
    &diams; Author of Oracle Application Express 3.2 – The Essentials and More

  • Problems with static member variables WAS: Why is the static initializer instantiating my class?!

    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

    Hi Eric,
    JDO calls the no-args constructor. Your application should regard this constructor as belonging
    primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
    values since that effort is wasted by JDO's later initilization to persistent values. Typically all
    you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
    rule means that you need initialization after construction if your application uses the no-args
    constructor and wants persistent fields initialized. On the other hand, if your application really
    uses constructors with arguments, and you're initializing persistent fields in the no-args
    constructor either unintentionally through field initializers or intentionally as a matter of
    consistency, you will find treating the no-args constructor differently helpful.
    On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
    Spec Section 20.16: "The generated static initialization code is placed after any user-defined
    static initialization code."
    David Ezzio
    Eric Borremans wrote:
    >
    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • Exception in static initializer

    Hi,
    I have one class with one static variable.
    I am initializing this variable in static initializer block. But while initializing, it is throwing some checked exception which I dont want to catch in block.
    Static initializer block doesn't support "throws", what should be done?
    Thanks

    hm..
    I think it depends on implementation.. etc
    Anyways, point is not where I should catch the
    exception. Point is, how can I throw the exception to
    caller when I am initializing static members. I don't think this makes sense! The 'caller' has to be the class loader so unless you are using your own class loader then you don't have any real choice.
    You could always wrap the exception in an un-checked exception and let the system handle it but this may just close the application anyway!

  • Uncaught exception: Static initializer: java/lang/SecurityException

    So i'm trying to compile some code of a small game for Doja.
    The code compiles fine but when i load it in the emulator i get the following eror:
    Uncaught exception java/lang/Error: Static initializer: java/lang/SecurityException.
    Now i haven't seen that before. I looked into it and first i thought there must be some static initializer block in some class but there isn't.
    Now i'm kinda stumped. What else can be the problem?

    A security exception is usually thrown when you try to use some function of the API that you're not allowed to use.
    For example, if the user has not given your application permission to connect to the internet, but you try to do so.
    Sometimes this error can be resolved by turning on the appropriate option in the ADF file.
    Cheers,
    Sam

  • How to force subclass static initialization?

    Interesting problem. Here's the setup:
    public class Properties1 implements Properties1Keys {
    private void Hashtable ht = new Hashtable();
    static { ht.put(prop1Key, "Test1"); }
    public static Object get(String key) { return ht.get(key); }
    public static void put(String key, Object o) { ht.put(key, o); }
    public interface Properties1Keys {
    public final static String prop1Key = "prop1";
    public class Properties2 extends Properties1 implements Properties2Keys {
    static { put(prop2Key, "Test2"); }
    public interface Properties2Keys {
    public final static String prop2Key = "prop2";
    Now, if the first thing we do is Properties2.get(Properties2.prop2Key) we will get a (null,) because no fields or methods from Properties2 have been accessed, and the static initializer is not executed.
    How can we automatically force Properties2 static initialization without either declaring some dummy method to be called first or reimplementing Properties1 methods. Properties1 is extended to import it's keys. Implementing Properties1Keys is not an option because further subclasses of this will need to implement all the stuff above it. This would be the most elegant solution (I think) but it fails to initialize because of the VM spec.
    Is the only solution a semi-screwy singleton?

    Interesting problem. Here's the setup:Unless I am reading something wrong that code makes absolutely no sense.
    public class Properties1 This class has a static initializer. Static initializers are called when the class is loaded. Static initializers have nothing to do with instances of the class. Just as static methods have nothing to do with instances of a class.
    The static initializer in Properties1 is calling a member variable. A variable that does not even exist in the context of a static initializer. That should be all that needs to be said on the subject.
    Lets presume that ht should have been static (since everything else is static.)
    When the class Properties2 is loaded one of the first things that occurs is that the parent classes are also loaded. Thus Properties1 is loaded. And likewise Properties1Keys is loaded.
    When Properties1Keys is loaded, it assigns the value to prop1Key. Thus when the static initializer of Propperties1 runs, prop1Key will have a value.
    Perhaps the problem lies in thinking that the values are initialized when the methods are accessed rather than when the classes are loaded?
    And in actual point of fact, because the values are declared 'final' it does not matter if prop1Key is initialized or not. Because the compiler will have already optimized the variable away. Consequently the code will be doing basically the following:
    static { ht.put("prop1", "Test1"); }
    This is relevant if the interface Properties1Keys changes and all of the dependent classes are not rebuilt. The values will not match.

  • Is static initialization of a class varaible guaranteed to occur only once?

    In other words, if two threads attempt to create an instance of this class, would the static initialization of ConnectionFactory occur once?
    public ConnectionSource {
    private static ConnectionFactory factory = new ConnectionFactory();
    I need exactly one instance of ConnectionFactory.
    SAF

    if ConnectionSource is unloaded (because there are no references to any instances on ConnectionSource, and no reference to the Class object itself), then a different ConnectionFactory would be created when the class is reloaded. This may or may not affect your program execution.
    Hackmann

  • JNDI lookup in Static initializer

    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was received for:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problem if
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

    Check the class loader and thread dump during the place where it works and
    the one where it doesn't ... that could help track down why it works that
    way.
    Peace,
    Cameron Purdy
    Tangosol Inc.
    << Tangosol Server: How Weblogic applications are customized >>
    << Download now from http://www.tangosol.com/download.jsp >>
    "Manish Shah" <[email protected]> wrote in message
    news:[email protected]..
    Hi,
    Is there a problem looking up home interfaces in a static initializer in
    WL6.1?
    I have a class X which runs in my application client. It has a static
    initializer that looks up a home interface. The call to Context.lookup()
    times out with weblogic.rjvm.PeerGoneException: No message was receivedfor:
    '240' seconds.
    The strange thing is, if I force the static initializer to run myself (by
    instantiating X directly), then it runs ok. I only get the above problemif
    the VM causes it to run (by loading a class Y that references X).
    Also, this behaviour is only apparent in the client. In the app server, X
    behaves correctly. I'm passing in JNDI properties as system properties on
    the command line to the client.
    Any help appreciated.
    Cheers,
    Manish

  • Huge volume of records are routing to the remote user other than his position and organization records. Synchronization and DB initialization taking more time around 36 hours.

    Huge volume of records are routing to the remote user other than his position and organization records. Synchronization and DB initialization taking more time around 36 hours.
    Actual accounts & contacts need to be route around 2000 & 3000 but we have observed lakhs of records routing into local DB.
    We have verified all the Assignment Rules, Views.
    We ran docking object visibility rules and we have observed that some other accounts are routing due to Organization rule passing. (these records are not supposed to route).
    Version Siebel 7.7.2.12,
    OS Solaris.

    let me know what would be the reason that 1st million takes only 15 minuts and the time goes on increasing gradually with the increase of dataYes that's a little strange. I only can guess:
    1. You are in archivelog mode and the Archiver is not able to archive the redo logs fast enough
    2. You don't use Direct Load and DBWR ist not able to write the direty block to disk fast enough. You could create more DBWR processes in that case.
    3. Make a snapshot of v$system_event:
    create table begin as select * from v$system_event;After the import run
    create table end as select * from v$system_event;Now compare the values:
    select * from begin order by TIME_WAITED_MICRO descwith the values given you by
    select * from end order by TIME_WAITED_MICRO descSo you can look where your DB spent so much time waiting for something.
    Alternativly, you could start a 10046 trace on the loading session and use tkprof.
    Dim

Maybe you are looking for