Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Float constant null when executing the static block?

The following code, when executed, prints nitesh null instead of the expected nitesh 130. Why isn't n initialized before executing the static block?

class test
{
      static
      {
             System.out.println(test.str+"   "+test.n);
      }
      final static String str="nitesh";
      final static Float n=130f;
      public static void main(String []args)
      {
      }
}
like image 746
Nits Avatar asked Jun 13 '14 10:06

Nits


1 Answers

str is a compile-time constant - n is not, because it's of type Float. If you change it to final static float n = 130f then you'll see the value in the static initialization block.

So currently, in the static initializer block, the value of str is actually being inlined - your code is equivalent to:

System.out.println("nitesh   "+test.n);

From JLS section 15.28 (constant expressions):

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: [...]

Float is not a primitive type.

Additionally, even without the inlining, the constant variable str is initialized before any of the static initializer blocks are executed. From section 12.4.2 of the JLS (class initialization details):

  • ...
  • Then, initialize the static fields of C which are constant variables (§4.12.4, §8.3.2, §9.3.1).
  • ...
  • Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
like image 90
Jon Skeet Avatar answered Nov 15 '22 21:11

Jon Skeet