5

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if I access it like File f = Logger.log I'm creating a new instance of the class.
File f = Logger.log creates a new reference to the single file that was already instantiated.
0

Just once. AFAIK, when class is loaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.