Unsure about static variables.
import java.io.File;
public class Logger {
public static final File log = new File(File.listRoots()[0], "log.log");
public static void log (String message) {
/* ... */
}
}
Is the variable log
pointing to the same memory throughout the life of the program? Basically is the log
definition new File(File.listRoots()[0], "log.log")
calculated multiple times or just one, and when?
Thanks in advance.
Static keyword can be used with class, variable, method and block. Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without object.
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
It is invoked once per classloader. Which, normally, means once.
A static variable is initialized as soon as the class declaring it is loaded by the classloader, and stays there until the classloader is destroyed, which in most cases means - at the end of the program execution / application lifecycle.
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