title: How to initialize a local variable in Java only once
body: <p>In C++, the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  static const char *init()
  {
      printf("in init()\n");
  }
  
  static void func()
  {
      static const char *str = init();
      printf("in func()\n");
  }
  
  int main()
  {
      for (int i=0; i&lt;10; ++i) {
          func();
      }
      return 0;
  }
  </code></pre>
  
  <p>shows that the despite the numerous invokations of the <em>func()</em>, <em>str</em> is only initialized once by printing a trace message in the function <em>init()</em> used to initialize <em>str</em>.  When run, there are a total of 10 lines of trace, once for <em>init()</em> and 10 times for <em>func()</em></p>
  
  <p>In Java, shouldn't the following code do the same thing?</p>
  
  <pre><code>class test {
      private String init()
      {
          System.out.println("in init()");
          return "FOO";
      }
  
      private void func()
      {
          final String str = init();
          System.out.println("in func()");
      }
  
      public test()
      {
          for (int i=0; i&lt;10; ++i) {
              func();
          }
      }
  
      public static main(String[] args)
      {
          test app = new test();
      }
  }
  </code></pre>
  
  <p>When run, there are 20 lines of output, 10 each for <em>init()</em> and <em>func()</em>.
  Based on what I read about <em>final</em> variables, I thought it would behave the same way.
  So I tried <em>static final</em> and it would not compile (nor just <em>static</em>)
  Is there a way to do this?  I need to call a time-consuming initialization function from
  several different methods in my class, so just moving the variable to class scope wouldn't work.
  Further, since local variables are not automatically initialized, I cannot include an <em>if</em> test for <em>null</em> around the variable before assigning it a value.
  I suppose I could create a variable at in the class scope for each method in my class, but
  managing it would be a pain to manage.
  The best analogy would be something if I were to include something like the following in every method:</p>
  
  <pre><code>public myfunc1()
  {
      final String funcName = java.lang.Thread.currentThread().getStackTrace()[1].getMethodName();
  }
  public myfunc2()
  {
      final String funcName = java.lang.Thread.currentThread().getStackTrace()[1].getMethodName();
  }
  </code></pre>
  
  <p><em>funcName</em> in this case will get a unique value in each method, but the initialization is expensive.</p>