简体   繁体   中英

Uninitialized static variable in memory in Java

In the example below, is memory allocated to j? If so, can the j's address change throughout the program assuming that j will never be initialized?

public class c{
    private static String j;
    public c(){}
    ....
}

The JVM will lazy load a class. Upon first reference to the class, the class will be allocated and yes memory will be laid out for all of the static fields. In this case, j will hold 'null'. Where the class and its fields will be allocated will depend on the JVM, and most specifically the Garbage Collector that was selected.

The Java language does not give direct access to the underlying memory address as other languages such as C do. And yes, the underlying memory address may change as/when/if the Garbage Collector decides to relocate the class; Some GCs will not relocate classes, the old ones could not even reclaim them. It is important to note that any move by the GC is not visible to the Java program. That is, so long as you avoid using sun.misc.Unsafe, sun.misc.Unsafe is a back door to the JVM that was added in Java 5.

For more details on Unsafe, this blog has a nice overview.

First of all, it is Java . Therefore no talking of address accessing and address change.

The compiler does all this on the behalf of the user for the optimisation and efficiency of the program.

Next, as the variable j has been declared static, you can't decide about the address, but its value will be permanent on declaration even after the end of its block, unless changed. (It means it doesn't lose the value even after the blocks accessing it and declaring it change.)

It'll only lose its value after termination of the program!

In the example below is memory allocated to j?

Memory is allocated by the JVM to the frame that includes the j static variable. And it will be default initialized to null . However, null does not refer to any heap node.

If so, can the j's address change throughout the program assuming that j will never be initialized?

It is not specified, but based on my understanding of how JVMs are typically implemented, yes the address of j could change.

However, unless a program tries to access j from native code (or equivalent), it won't be aware of the address, or possible changes to it.

You can say it will just point to null reference. Memory in Java is allocated using dynamic memory operator ie new operator (some class like String have special privileges that it can be initialized using = operator).

Java is not C ... every piece of data (even static variables) gets implicitly initialized (often to null or 0), and the compiler won't accept uninitiliazed local variables. Found this explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM