As part of JVM Loading, Linking and Initalizing, When the
static fields
final static fields
in Class
allocating in memory
init as default value
init as real value
In the case of the static final variables, I think that everything happens in the Loading step, because all values are already in Constant Pool.
But I can not figure out what's going on with the static fields. In principle, in the written documantation that they are initialized with default value in the Preparation step.
Preparation involves creating the static fields for a class or interface and initializing such fields to their default values (§2.3, §2.4). This does not require the execution of any Java Virtual Machine code; explicit initializers for static fields are executed as part of initialization (§5.5), not preparation.
But in this source (Class Variables paragraph) loading the static fields initialization occurs already in the Loading step. This makes sense because at the end of the loading step an instance of the class object is created, and it must contain room for the static fields.
Before a Java virtual machine uses a class, it must allocate memory from the method area for each non-final class variable declared in the class.
So I'd like to know what the right fact is in this case.
Generally, if there is some mismatch between the official specification and some article on the internet, you can safely assume that the specification has the last word and the article is wrong. This will serve you in 99.99% of all cases.
That’s especially true when it comes to the Java Virtual Machine, where articles notoriously mix up the steps of your question (“Loading, Linking, and Initializing”), and also regularly mix up formal steps and implementation details.
The article you’ve linked, does it wrong in several aspects:
Not every static final field is a compile-time constant. Only static final fields of primitive types or String are compile-time constants, if they are immediately initialized with a compile-time constant. Consider
static final String CONSTANT1 = ""; // compile-time constant
static final String CONSTANT2 = CONSTANT1; // compile-time constant
// but
static final String NO_CONSTANT1 = CONSTANT1.toString(); // not a constant expression
static final String NO_CONSTANT2; // no initializer
static {
NO_CONSTANT2 = ""; // assignment in class initializer, valid, but not constant
}
static final BigInteger NO_CONSTANT3 = BigInteger.ONE; // neither primitive nor String
For compile time constants, every ordinary Java language read access is replaced by the constant value at compile-time, still, the identifiers exist and can be inspected via Reflection or accessed by byte code not generated from Java language source code. Whether the JVM treats constant fields specially, when it comes to their storage, is an implementation detail, but usually, implementors try to avoid special treatment, unless there’s a true benefit.
The formal specification describes the constant variables as-if having a storage like any other variable, but of course, implementations may omit this, if they are capable of still retaining the mandated behavior (e.g. make the values available to Reflection).
The initialization of both, constant and non-constant static variables is clearly specified as part of the Initialization (though not at the same time):
Otherwise, record the fact that initialization of the Class object for C is in progress by the current thread, and release LC. Then, initialize each final static field of C with the constant value in its ConstantValue attribute (§4.7.2), in the order the fields appear in the ClassFile structure.
…
9. Next, execute the class or interface initialization method of C.
The “class or interface initialization method” is the method named <clinit> at the bytecode level, which contains all initializers of non-constant static fields as well as any code in static { … } blocks.
Class variables and the constant pool are different things. The constant pool contains the symbolic names of fields as well as values for compile-time constants (which, by the way, may include non-static fields as well).
The values of the constant pool can be used to construct the actual runtime values, e.g. the byte sequence describing a string has to be converted to a reference to an actual String object and the primitive types may undergo Endianess conversions. When this processing happens as part of step 6 described in JVMS§5.5, as cited above, subsequent access to the field will consistently use the result of this process.
My understanding is that the memory allocation is done during the preparation, and the execution of the initializers during initialization. This doesn't contradict either of the sources.
To be precise,
Instance variables will be stored on the heap.
local variables on the stack(in case of variable not a
primitive[reference variable] reference variables live on stack and
the object on heap ). Only method invocation and partial results will
be stored in stack not the method itself.
Static variables and Methods(including static and Non Static) on the
Method Area. Static methods (in fact all methods) as well as static variables are stored in the PermGen section , since they are part of the reflection data (class related data, not instance related).
For static variables, if you do not initialize a variable, default value would be stored before object preparation (JVM takes care of this) but for Final Static, you need to initialize the variable before the object is created i.e. when we try to create a new object calling the constructor, before the object is returned to the reference variable, value need to be initialized else it is a compile time error.
Answers to your questions:
Static variable in Java belongs to the class and
initialized only once when the class is invoked (if not initialized - Lazy Initialization).
Static final variable is initialized at the time of class loading in
the method Area, as it is already initialized in the code (early initialization).
There wont be any change in the allocating in memory for static and final static.
public class Object {
public static final int i;
static{
i=0; // comment this line gives you compile time error
}
/**
* #param args
*/
public static void main(String[] args) {
}
}
Related
Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.
This is a very wide-spread enum singleton code:
public enum enumClazz{
INSTANCE
enumClazz(){
//do something
}
}
and a bunch of places said it is a lazy initialization. But I am confused after I read Chapter 7 of 'Inside the Java Virtual Machine' -- The Lifetime of a Type:
The Java virtual machine specification gives implementations
flexibility in the timing of class and interface loading and linking,
but strictly defines the timing of initialization. All implementations
must initialize each class or interface on its first active use. The
following six situations qualify as active uses:
A new instance of a class is created (in bytecodes, the execution of a new instruction. Alternatively, via implicit creation,
reflection, cloning, or deserialization.)
The invocation of a static method declared by a class (in bytecodes, the execution of an invokestatic instruction)
The use or assignment of a static field declared by a class or interface, except for static fields that are final and initialized by
a compile-time constant expression (in bytecodes, the execution of a
getstatic or putstatic instruction)
The invocation of certain reflective methods in the Java API, such as methods in class Class or in classes in the java.lang.reflect
package
The initialization of a subclass of a class (Initialization of a class requires prior initialization of its superclass.)
The designation of a class as the initial class (with the main()< method) when a Java virtual machine starts up
The third point with bold style clarify that if the field is static final, the initialization of the field is happened at compile-time. Likewise, the INSTANCE in enumClazz is implicitly equal to public static final and comply with the third point.
Can someone correct me if my understanding is wrong?
enum instance fields are not "initialized by a compile-time constant expression". They
can't be, because only String and primitive types are possible types for a compile-time constant expression.
That means that the class will be initialized when INSTANCE is first accessed (which is exactly the desired effect).
The exception in the bold text above exists, because those constants (static final fields initialized with a compile-time constant expression) will effectively be inlined during compilation:
class A {
public static final String FOO = "foo";
static {
System.out.println("initializing A");
}
}
class B {
public static void main(String[] args) {
System.out.println(A.FOO);
}
}
Executing class B in this example will not initialize A (and will not print "initializing A"). And if you look into the bytecode generated for B you'll see a string literal with the value "foo" and no reference to the class A.
The third point with bold style clarify that if the field is 'static final', the initialzation of the field is happened at complie-time
Not exactly - it only applies to "static fields that are final and initialized by a compile-time constant expression":
static final String = "abc"; //compile time constant
static final Object = new Object(); //initialised at runtime
In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code.
So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.
I ran into an interesting thing:
static {
System.out.println(test); // error cannot reference a field before it is defined
System.out.println(cheat()); // OK!
}
private static boolean cheat() {
return test;
}
private static boolean test = true;
public static void main(String args[]) {}
The first way is wrong and both your compiler and IDE will tell you it's wrong. In the second case, cheating is OK, but it actually defaults the field test to false. Using Sun JDK 6.
This is defined in the JLS 8.3.2.3. In particular:
The declaration of a member needs to appear textually before it is used [...] if the usage occurs in a [...] static initializer of C.
When you call cheat() you go around that rule. This is actually the 5th example in the list of the examples of that section.
Note that cheat() will return false in the static initializer block because test has not been initialised yet.
Because class loading works in this order:
Loads Class definition (methods, signatures)
Allocates the memory for the static variable references (for test) - does not initialize yet
Executes the static initializers (for variables) and the static blocks - in order they are defined
So, by the time you have reachstatic block, you have the method definition ready, but don't have the variable ready. With cheat() you're actually reading an uninitialized value.
This is the generic steps by which class loading happens.
Loading - Load the class to memory
Verification - checks binary representation of a class e is correct
Preparation - create the static fields for the class and initialize those fields to their standard default values.
Initializing - will invoke static initializers and initializers for static fields
After preparation, your test will be false.Then before you assign static variable to true, your static block will execute.That is why you are getting false.
Try making your static variable final.In that case,you will be getting true.This is because your compiler itself will embed the value in bytecode(since the field is final) as part of optimisation
Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.
I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?
A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?
The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.
public static void main(String args[])
{
final int a=0; //ok
int b=1; //ok
static int c=2; //wrong
final static int x=0; //wrong
}
You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.
Anyways, these are the concepts you are mixing up:
variables
final variables
fields
final fields
static fields
final static fields
The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).
Let's try to rapidly describe them.
variables are declared in methods, and used as some kind of mutable local storage (int x; x = 5; x++)
final variables are also declared in methods, and are used as an immutable local storage (final int y; y = 0; y++; // won't compile). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final. Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).
fields define the mutable state of objects, and are declared in classes (class x { int myField; }).
final fields define the immutable state of objects, are declared in classes and must be initialized before the constructor finishes (class x { final int myField = 5; }). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).
static fields are shared among all instances of any class. You can think of them as some kind of global mutable storage (class x { static int globalField = 5; }). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } }, here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x()). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).
final static fields are global constants (class MyConstants { public static final double PI = 3.1415926535897932384626433; }).
There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.
Finally, there are also other keywords that might be used with fields, like transient, volatile and the access levels (public, protected, private). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).
Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.
Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant".
I'm unable to differentiate between a final and a final static member.
The final static member is the one which is a static member declared
as final or something else? In which particular situations should they
be used specifically?
Use a final static when you want it to be static. Use a final (non-static) when you don't want it to be static.
A static variable or a final static variable can never be declared
inside a method neither inside a static method nor inside an instance
method. Why?
Design decision. There's just no way to answer that without asking James Gosling.
The following segment of code accordingly, will not be compiled and an
compile-time error will be issued by the compiler, if an attempt is
made to compile it.
Because it violates the rule you just described.
final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant.
On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.
In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.
A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.
final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.
Just to add a minor information to #Bruno Reis 's answer, which I sought to complete the answer, as he spoke about important condition to initialize final fields before constructor ends, final static fields must also be initialized before before static blocks' execution finishes.
You cannot declare static fields in static block, static fields can only belong to a class, hence the compiler error.
When you declare a final variable (constant) in a class, for example:
private static final int MyVar = 255;
How much memory will this require if I have 100,000 instances of the class which declared this?
Will it link the variable to the class and thus have 1*MyVar memory usage (disregarding internal pointers), or will it link to the instance of this variable and create 100,000*MyVar copies of this variable?
Unbelievably fast response! The consensus seems to be that if a variable is both static and final then it will require 1*MyVar. Thanks all!
The final keyword is irrelevant to the amount of memory used, since it only means that you can't change the value of the variable.
However, since the variable is declared static, there will be only one such variable that belongs to the class and not to a specific instance.
Taken from here:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized . A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
There will be only 1*MyVar memory usage because it is declared as static.
The static declaration means it will only have one instance for that class and it's subclasses (unless they override MyVar).
An int is a 32-bit signed 2's complement integer primitive, so it takes 4 bytes to hold it, if your example wasn't using static you'd just multiply that by the number of instances you have (for your example of 100,000 instances that's 0.38 of a megabyte - for the field alone, extra overhead for actual classes).
The final modifier on a field means it cannot be repointed to another value (whereas final on a class of method means it cannot be overridden).
It's static and thus class scope -> 1.
Edit: actually, it depends on the class loaders. In the general case you have one copy of the class but if you have multiple class loaders/class repositories (might be the case in application servers etc.) you could end up with more.
In addition to the fact that static fields belong to their classes, and thus there is only one instance of static varaible per class (and per classloader), it's important to understand that static final variables initialized by compile-time constant expressions are inlined into classes that use them.
JLS §13.1 The Form of a Binary:
References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed.
So, in practice, the instance of static final variable that belong to its class is not the only instance of value of that variable - there are other instances of that value inlined into constant pools (or code) of classes that use the variable in question.
class Foo {
public static final String S = "Hello, world!";
}
class Bar {
public static void main(String[] args) {
// No real access to class Foo here
// String "Hello, world!" is inlined into the constant pool of class Bar
String s = Foo.S;
System.out.println(s);
}
}
In practice it means that if you change the value of Foo.S in class Foo, but don't recompile class Bar, class Bar will print the old value of Foo.S.
static means you will have only one instatnce
final just means, that you can't reassign that value.
The crucial part here is that you declared the variable as static because static variables are shared among all instances of the class, thus requiring only as much space as one instance of the variable. Declaring a variable final makes it immutable outside its declaration or constructor.
final makes is 1*instances memory usage.
However, static makes it simply 1.
The keyword "final" helps you to declare a constant with a specific amount of memory, where as the keyword "static" as its prefix will gives a single instance of this constant, what ever be the amount of memory consumed...!!!
Static means, one instance per class, static variable created once and can be shared between different object.
Final variable, once value is initialized it can't be changed. Final static variable use to create constant (Immutable) and refer directly without using the object.
It's static, so there will be only one instance created, so however many bytes are required to hold one int primitive will be allocated
You will have one instance per class. If you have the class loaded more than once (in different class loaders) it will be loaded once per class loader which loads it.
BTW: Memory is surprising cheap these days. Even if there was a copy per instance, the time it takes you to ask the question is worth more than the memory you save. You should make it static final for clarity rather than performance. Clearer code is easier to maintain and is often more efficient as well.