Initialization of the static variable

When does it happening; Is it happening during the compilation time or when the class is loaded or when the first instance of the class is created?
can't find it anywhere in docs

There's one common gotcha with static fields. Compile and run this code:
public class One {
    public static final int CONSTANT = 17;
public class Two {
    public static void main(String[] args) {
        System.out.println(One.CONSTANT);
}You get the output 17 -- no surprise. Now edit One.java and change that value to 42, say, and
carefully only recompile One.java. (You may not want to do this
in an overly helpful IDE!) When you run Two again, you will still see 17!
To avoid this, you can use a static initializer:
public class One {
    public static final int CONSTANT;
    static {
        CONSTANT = 42;
}

Similar Messages

  • 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 use the dynamical or static variable for ESSBASE cube name?

    Hi Experts,
    When I import ESSBASE Cube into physical layer, the cube name from ESSBASE is created automatically, such as H_Sales.
    I want to use the the static or dynamical variable for replacing the external name. So I try to create the static variable in RPD,such as cubeName, and use the following code
    'VALUEOF(cubeName)' into the textbox of external name.
    However, when I view the report in answer, it will generate the error message: Database VALUEOF(cubeName) does not exist.
    Is it possible to implement this functionality?
    Thanks..

    Hi,
    use <%=odiRef.getSchemaName("D")%>
    D as parameter if it is the Data Schema or W if you need the schema from Work Schema
    Your command will be like:
    select <%=odiRef.getSchemaName("D")%>.GER_LOT_EXEC_ODI('Fluxo', 1, 'C') FROM DUAL
    Works?
    Cezar Santos
    http://odiexperts.com

  • How to load value to a static variable on the run

    hi all
    i have a question about static variable. i need to have a variable to keep a value from DB shared by all instances. the variable is given value when the first instance is created. but from time to time, the value in DB may change, but i still need to maintain this shared value among instances. the static variable has life time as long as the program runs, does that mean if i need to change the value, i need to stop the program, and restart to load the new value? thanks.

    can the static variable be accessed within a
    non-static method, for instance, set the value by
    setXXX() method?Yes, and oddly enough, that usually how I access all my variables...
    Example...
    public class StaticTester {
           static String theString = " My Message ";
           public void setMessage(String mess){
                      theString = mess;
           public String getMessage(){
                      return theString;
           public static void main(String[] theArgs){
                      StaticTester myTest = new StaticTester();
                    System.out.println(myTest.getMessage());
                    myTest.setMessage(" a New Message ");
                 System.out.println(myTest.getMessage());
    }Hope this helps...
    - MaxxDmg...
    - ' He who never sleeps... '

  • Shared java static variables

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

    I have an application where I would like to
    read from some small configuration tables
    and cache them into java variables, in order to avoid each stored procedure call to redo
    those queries. The configuration data is
    pretty static, so I don't worry about refresh
    problems.
    My first attempt to do that was using static
    final variables (like Vector). In our oracle
    environment however (8.1.7) each session
    seems to have its own copy of static final
    variables, resulting in each session to
    perform those queries for initializing all
    over again.
    firstly, i would like to find out if there is another way to share this data among java
    sessions, but otherwise I am curious how
    I can get the claims made in http://technet.oracle.com/products/oracle8i/pdf/8ir2java.pdf , page 6 to work.
    Specifically, here is what the document says:
    "In Oracel8i Release 2, JServer introduces the concept of "hotloaded" classes. Various core classes that
    initialize static variables known to be constant are pre-initialized during database creation time. When you use
    one of these classes in your program, the class loader loads the pre-initialized form. In many cases, the time
    required to initialize the static variables is itself quite significant, and now with the introduction of hotloaded
    classes that time is completely eliminated. In addition, the objects in these particular static variables are shared
    among all sessions. Hotloaded classes therefore improve performance by eliminating class initialization and
    they reduce per-user-session footprint by increasing the amount of data shared between sessions. Hotloaded
    classes provide improved performance and scalability "for free", with no user intervention. "
    the kind of initialization I have been
    trying is like:
    public static final int inti = func();
    this also didn't seem to work:
    public static final int inti;
    static {
    inti = ....;
    thanks,
    null

  • Static variable behaviour in memory

    Hi,
    My question is :
    When you compile a java code, does the static variable gets the memory allocated while creating the byte code or is it on run time that a static variable gets the memory allocation and then it is shared for all instances.
    Thanks
    Melvyn.

    Good !!! I expected this question from you.
    Instantiation and Initialization are different.
    A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
    1) T is a class and an instance of T is created.
    2) T is a class and a static method declared by T is invoked.
    3) A static field declared by T is assigned.
    4) A static field declared by T is used and the reference to the
    field is not a compile-time constant. References to
    compile-time constants must be resolved at compile time to
    a copy of the compile-time constant value, so uses of such a
    field never cause initialization.
    Regards
    Raghu

  • Static Variable using Dynamic Variable

    I have a need to display different variations of the current date across multiple reports - for example: YYYYMM, MMYYYY, YYYYDD, etc.
    I thought I could create an initialization block that maps three variables containing - YYYY, MM and DD.
    In the Static Variable I was going to do the different concatenation of these variables. I see in the Static Variable it allows me to go in and select repository variables in the Expression Builder, so if had two Dyanmic Variables (VarYYYY and VarMM) I select these for my new Static Variable and concatenate them (Valueof(VarYYYY) || Valueof(VarMM).
    However, when I go to the report and display this variable it displays just the text above, treating it like a string value, so all I see in the report is:
    Valueof("VarYYYY") || Valueof("VarMM")
    I am referencing in the report with the syntax
    @{biServer.variables['StaticVarName']}
    Is there a reason why it does not display the variable values?
    Thanks

    mmm some solution could be to write the same insert with decode/case statement and put there the conditions that you want.
    maybe something like this:
    SQL> ed
    Wrote file afiedt.buf
      1  begin
      2    for i in 1..10 loop
      3      insert into t1 (col1,col2,col3)
      4        values (i,
      5                decode (mod (i,2),0,i,null),
      6                decode (mod (i,3),0,i,null));
      7    end loop;
      8* end;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> select * from t1;
          COL1       COL2       COL3
             1
             2          2
             3                     3
             4          4
             5
             6          6          6
             7
             8          8
             9                     9
            10         10
    10 rows selected.
    SQL> truncate table t1;
    Table truncated.
    SQL> insert into t1 (col1,col2,col3)
      2    select rownum,
      3           decode (mod (rownum,2),0,rownum,null),
      4           decode (mod (rownum,3),0,rownum,null)
      5    from dual
      6  connect by rownum <=10;
    10 rows created.
    SQL> select * from t1;
          COL1       COL2       COL3
             1
             2          2
             3                     3
             4          4
             5
             6          6          6
             7
             8          8
             9                     9
            10         10
    10 rows selected.forgot that you are not using anymore the loop :)
    Message was edited by:
    Delfino Nunez

  • JUnit Test Debug: Static variable lost value!!!

    Hi, I am writing JUnit code.
    env: JDeveloper + JUnit Plugin + Selenium RC
    While I am debugging, I found the static variable lost between 2 different test, I mean a test is a @Test, do somebody know why??
    Thank you very much!!

    1.) The File you initialize in the method is not the same as the instance file variable that you initially initialized to null. You declared a new File in that method.
    2.) Read about layout managers. The behavior you are seeing is because of the default layout manager's behavior.

  • Local static variable not unique between dylib, Xcode 4.4.1 bug?

    I am wondering if this is a Xcode bug or it is the way the c++ standart is.
    I would expect to  see 1 in the console but i see 0.
    Anybody know why? Here is the code
    In one dylib I have
    // Header file
    class Foo {
       int i_ = 0;
       Foo(const Foo&) = delete;
       Foo& operator= (Foo) = delete;
       Foo()
    public:
       void inc()
          ++i_;
       int geti()
          return i_;
       static Foo& get()
          static Foo instance_;
          return instance_;
       Foo( Foo&&) = default;
       Foo& operator= (Foo&&) = default;
    int initialize()
       Foo::get().inc();
       return 10;
    class Bar
       static int b_;
    // cpp file
    #include "ClassLocalStatic.h"
    int Bar::b_ = initialize();
    and in my application project i have
    // main.cpp
    #include <iostream>
    #include "ClassLocalstatic.h"
    int main(int argc, const char * argv[])
       std::cout << Foo::get().geti();
       return 0;
    Thanks

    thanks for your answer, You are right there is 2 foo singleton at different memory addresses.
    I didn't think about when the dylib was loaded. I can't even tell when it is loaded. But I know if i but breaks point I break in the initialize function before breaking in main, but that might be because of this actual setup. So when does a dylib will be loaded? At the first call a program sees that need the dylib?
    Here I'explain why it is done this way. My Singleton is a UnitTestRegistry, the Bar class is a UnitTest class and the static variable b_ is a class containing metadata info on the unit test.
    I have a macro to define the unit test it is called Make_UnitTest()
    So in a cpp I do
    Make_UnitTest(MyTest)
         // Test Stuff
    The macro will get expanded to
    class MyTest_UnitTest: public UnitTestBase
         static UniTestMetaData b_;
         virtual void executeTest();
    int MyTest_UnitTest::b_ = initializeAndRegisterUnitTest("MyTest_UnitTest", factoryFunction);
    MyTest_UnitTest::executeTest()
    // Test Stuff
    And in the function initializeAndRegisterUnitTest I call the getInstance of the unit test  registry. This way my unit test are registred at loading time of the program/dll. If you know a better way to automatically register (i know it cuold be manual but i find it too cumbersome), but it wont fix the problem which is that I have two intance of my singleton because the function is inline in a header.
    Well this behavior is surprising to me, I didn't know it would do this. But hey it is good to learn right!
    Just to make it clear there is no real global!! The singleton is like a global but it is not completly one and the b_ is certainly not global it is a class static memeber...

  • Static variables in CLR stored procedures

    Is there really no way to use static variables shared by several CLS stored procedures in the same DLL, except by making them read only?
    Or can you add new server variables and read/write those from CLR stored procedures without having to open a connection and run a query each time you need a value?
    In my SP's, I would like to know the path where the database's .mdf file is stored on disk (not to access that file, but to store other files in a location that's always the same relative to the database).
    I thought I had found the solution last week, after some digging through sites like stackoverflow: make it a static read-only variable, and initialize it through a function call when the module is loaded.  The CLR will "forget" that it is
    read only at that time.
    For some reason this has worked perfectly for a week, but today it suddenly started failing -- without any code change or even a recompile, it started after a simple reboot of the test machine.
    The code (just the relevant lines, in VB syntax):
    Private Shared ReadOnly Datapath As String = InitDataPath()
    Private Shared Function InitDataPath() As String
    Try
    Using cn As New SqlConnection("context connection=true"),
    cmd As New SqlCommand("SELECT TOP 1 [physical_name] FROM sys.database_files WHERE type=0", cn)
    cn.Open()
    The "cn.open" line throws "Data access is not allowed in this context."
    It did not yet do that yesterday, and the day before, and all the way back to January 6th, when I wrote that piece of code.  The DLL hadn't even been recompiled since then, I was working on the application that uses the database and the stored procedures.

    I think I found it, at least it works again -- I just hope it's for more than a week now.
    Declare assembly as unsafe when installing it in SQL server (it was already 'EXTERNAL_ACCESS' for file I/O, but non-read-only static variables require UNSAFE).
    I initialize the static variables to 'Nothing' (NULL for C# users), and instead of finding the path when the module is loaded, I added a line 'if xxx is nothing then init()' at the start of each procedure / function. Init() is a a simple initialization
    routine that initializes the static variables upon first access.
    added SystemDataAccess:=DataAccessKind.Read to the declaration of UDF's (not possible and not necessary for procedures, apparently, but if what caused the assembly to load was a function, it would still fail).

  • Private,public and static variable

    I am just not able to understand the use of declaring the variable as private.Because even if i declare the variable as public ,other user of the same application anyway will never be acess that variable !! Can someone clear my doubt.
    Also can some one tell me when can I declare a variable as static...that is ideallly when should i declare a variable as static (and for that matter private and public )
    Thanks.
    Tha

    Hi,
    There are some rules for variable declarations:
    Only the containing class and its inner classes can access private variables.
    Every class can access public variables.
    All classes in the same package can access protected variables.
    Imagine you're writing a program for archiving all your CD's.
    If you want to know how many cd's you have got you simply read the static variable.
    public class CD {
    private String name, author;
    public static int cdCount = 0;
    public CD(String name, String author){
    //do something to initialize
    cdCount++; //Increase the value, because a new CD has been created.
    public static int getCDCount(){      //static methods can be accessed without creating instances of classes
    return cdCount;
    public static void main(String[] args){
    CD kravitz = new CD("Lenny Kravitz", "A Song");
    CD britney = new CD("Britney Spears", "Another Song");
    System.out.println("You have " CD.getCDCount() " CDs"); //You call static methods on the class (you can also call them on instances, but it is important that you do not need to create a object of that class)
    }

  • Inheritance & Static Variables

    Just a technical question...
    Class A has a static Variable -staticVar
    Class B extends Class A but defines a static variable with the same Name -staticVar
    Class A has a nonstatic method init(String inputString) that does
    staticVar = inputString;
    When an instance of Class B is instantiated
    bObject = new B();
    aObject = new A();
    bObject.init("Now Initializing B");
    For some reason, the init function (in class A but available to Class B as it extends) initializes the static variable of A and not B.
    Let's say if Class B overrides the init method, then it is able to set the value of the static variable of B.
    Why is it doing that?
    My impression was that all the nonstatic methods are in the object level. (No longer in the class level.) So if I create an instance of Class B, any method (either inherited or not inherited) should refer to the static variables of Class B.
    Thanks,
    V.

    What you have discovered is called variable 'hiding'. When you declare B to have a variable that has the same name as one in A, they are two completely different varaibles.
    Variables and static methods are not polymorphic in Java. When the init method is executing, it doesn't search the class inheritance tree for the most specific version of the variable named staticVar. The variable that will be used is determined at compile time. The variable names are discarded by the compiler and never used by the VM.

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • Runtime error in linking with static variables....

    Hi,
    I am building a shared library which includes a compiled object generated from a class containing the static variables only and also I have another version of same class with same & some new static variables in it and using that to generate another shared library. Now when I tried to run a program
    which links with both the library it core dumps when it tries to return from the program i.e when it finishes.
    Can someone please help me explain why my program is behaving like that?? Can duplicate inculsion of static variables in different scope can cause problem ?? How can this be avoided ?
    Also please be advised that the class with static variables gets generated at the compile time using a script which uses a DTD whose version (specification) can be different in both the libraries therefore I can't just seperate the common stuff into one class and specific into another.
    Thanks.
    Rajeev.

    Not to worry...found the answer in another post. Seems like patches need to applied to the OS.

Maybe you are looking for

  • Ms-7360 P35 Neo wo't boot with full 8GB DDR2

    Let's begin with me stating my problem: I recently bought these ddr2 modules: http://www.ocztechnology.com/products/memory/ocz_ddr2_pc2_6400_vista_performance_gold_4gb_dual_channel (2x2GB OCZ Gold PC2-6400) I already had 2x2gb Patriot ddr2 (http://ww

  • Windows 8.1 Hyper-V - Error while configuring the hard disk 0xC03A0014

    Hello. I have just enabled Hyper-V on my Windows 8.1 laptop. Dell Latitude E7440 i7-4600U @ 2.10GHz I can create a Virtual-Switch but I am unable to create a new Hard Disk or Virtual Machine within Hyper-V. I get the same error for both processes. Er

  • How to put the restrict in pf-status  in standard program

    hi friends, My requirement is if we give any values in ov51 tcode this all details will go to the one mail. but Client ask do want to the pf-status values how to restric pf-status values. Could any one help . This is sample code SUBMIT RFDABL00 TO SA

  • HOLDING / PARKING INVOICE DOCUMENT

    HELLO EXPERTS, What is the difference between holding a invoice document (MIRO) and parking a document (MIR7). I hope each having same function. Again I want to see a report which will show me hold invoice document Again what is the difference betwee

  • Read_error

    does anyone the reasons why you get a read_error from utl_file.get_line when trying to read a file on a unix server but the file(pdf) was generated on a windows server. i presume it has something to do with encoding but can anyone explain this furthe