PDA

Click to See Complete Forum and Search --> : Static Initializers


Dillinger4
Apr 3rd, 2001, 08:38 PM
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;
}
}

sweetsupra
Apr 4th, 2001, 11:52 AM
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????/
:p