Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java static class / variables

Tags:

java

static

final

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.

like image 562
Patrick Lorio Avatar asked Mar 29 '12 21:03

Patrick Lorio


People also ask

Can a static class have variables?

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.

Are static variables allowed in Java?

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.


1 Answers

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.

like image 137
Bozho Avatar answered Oct 19 '22 04:10

Bozho