Someone explain to me the differences between the following two statements?
A static final
variable initialized by a static
code block:
private static final String foo; static { foo = "foo"; }
A static final
variable initialized by an assignment:
private static final String foo = "foo";
Static methods belong to the class and they will be loaded into the memory along with the class, you can invoke them without creating an object. (using the class name as reference). Whereas a static block is a block of code with a static keyword. In general, these are used to initialize the static members.
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used to declare static classes. In classes, interfaces, and structs, you may add the static modifier to fields, methods, properties, operators, events, and constructors.
A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created. Static variables occupies less space and memory allocation happens once. A non-static variable may occupy more space.
In java, we can use the static keyword with a block of code that is known as a static block. A static block can have several instructions that always run when a class is loaded into memory. It is also known as java static initializer block because we can initialize the static variables in the static block at runtime.
In this example, there's one subtle difference - in your first example, foo
isn't determined to be a compile-time constant, so it can't be used as a case in switch
blocks (and wouldn't be inlined into other code); in your second example it, is. So for example:
switch (args[0]) { case foo: System.out.println("Yes"); break; }
That's valid when foo
is deemed to be a constant expression, but not when it's "just" a static final variable.
However, static initializer blocks are usually used when you have more complicated initialization code - such as populating a collection.
The timing for initialization is described in JLS 12.4.2; any static final fields which are considered as compile-time constants are initialized first (step 6) and initializers are run later (step 9); all initializers (whether they're field initializers or static initializers) are run in textual order.
private static final String foo; static { foo ="foo";}
The value of foo
is initialized when the class is loaded and static initializers are run.
private static final String foo = "foo";
Here, the value of foo
will be a compile-time constant. So, in reality "foo"
will be available as part of th byte-code itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With