什么时候初始化此静态变量,什么时候使用StringBuffer

时间:2020-05-29 09:00:29

标签: java

我刚刚看到了这个例子

field: partner_name
object: helpdesk.ticket

现在,当您调用Runtime.getRuntime()时,即使从未创建此类的实例,也已经初始化了currentRuntime。如何运作?

我的第二个问题是关于StringBuffer的?

public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();


    public static Runtime getRuntime() {
        return currentRuntime;
    }

现在,如果您执行String var = "Hello World";

使用StringBuffer更好吗?我的意思是StringBuffer至少保留了我认为至少1000Byte的大量内存,所以仅就该简单示例而言,最好不使用StringBuffer。当然 现在我们在内存中有2个字符串“ Hello World”和“ Hello World!”但是仍然优于1000字节或更多的StringBuffer。是吗?

1 个答案:

答案 0 :(得分:0)

我将回答:“何时初始化此静态变量”

我已经体验到需要时会加载Java类。例如,如果您从不使用它(例如,您从不引用变量或调用函数/构造函数),则JVM不会初始化该类。

因此,当您调用Runtime.getRuntime()时,该类将被初始化,静态字段也将被初始化。

您还可以使用带有此代码的静态块对其进行测试

public class MainClass {
    public static void main(String[] args) {
        System.out.println("program starts");
        Runtime.getRuntime();
        System.out.println("programs end");
    }
}
public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();

    static {
        System.out.println("when this is called the class is beeing initialized");
        System.out.println("is currentRuntime null? -> " + (currentRuntime == null));
    }

    public static Runtime getRuntime() {
        System.out.println("getRuntime is executed");
        return currentRuntime;
    }
}

这就是我在控制台上得到的

program starts
when this is called the class is beeing initialized
is currentRuntime null? -> false
getRuntime is called
programs end

这是什么意思? 。在main()启动之前初始化类Runtime(及其字段),但在请求Runtime 时将其初始化。

此外,当 currentRuntime 不为null时,将调用静态块,因此它已被初始化(请记住Java是自上而下的)。

因此,它是在调用Runtime.getRuntime()时但在执行之前初始化的