Results 1 to 2 of 2

Thread: Static Initializers

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    I read somewhere that instance fields are initialized
    in constructor methods. But class fields are actually
    initialized in a method that is hidded from the Java programmer. If one disassembles the Java byte codes in a Java class file one can see the class initialization code in a method name <clinit>

    Ok fine so this leads me to my question is the main purpose of a static initializer to initialize class fields to a value other then the default false or zero?

    or is static just a short hand was of defining a block
    of static class fields without specifying the static keyword for each and every class field.

    class test {
    static {
    double x = 1.5;
    int k = 5654;
    }
    }

  2. #2
    Lively Member
    Join Date
    Jan 2000
    Posts
    69
    Hey Dilenger4,

    Let's handle the first question:
    Quote:
    The main purpose of a static initializer to initialize class fields to a value other then the default false or zero?
    Most ppl tend to initialize variables at the beginning of the class for numerous reasons:
    1) Variables that will not change for example mathemathical constants( i.e. PI, gravitional constants, etc). They usually use private and final modifiers in this instances as well as static(sometimes).

    2) Secondly, I have noticed where static variables were used for purpose of counters. Since there is only one instance of that variable. Whenever a process is being updated, it may effect that counter. So, it is beneficial to keep one instance of that variable.

    3) It is just good practice to initialize variables at class loadings.

    static keyword doesn't replace the static block. The static blocks are used for the JVM to load all the info first with the use of static blocks. In other words JVM looks for all static blocks first and loads it. Only doubt I have is if the static blocks and main method is in the same class. I am not sure which will load first. I thint it will be the static blocks.

    Did it help, Dilenger4????/

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width