Java 何时初始化此静态变量以及何时使用StringBuffer
我刚刚看到这个例子Java 何时初始化此静态变量以及何时使用StringBuffer,java,Java,我刚刚看到这个例子 public class Runtime { //When is this private member initalised ?? private static Runtime currentRuntime = new Runtime(); public static Runtime getRuntime() { return currentRuntime; } 现在,当您调用Runtime.getRuntime()时,
public class Runtime {
//When is this private member initalised ??
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
现在,当您调用Runtime.getRuntime()时,currentRuntime已经初始化,即使从未创建过此类的实例。它是如何工作的
我的第二个问题是关于StringBuffer的
String var = "Hello World";
现在,如果您执行var=var+“!”代码>
使用StringBuffer会更好吗。我的意思是StringBuffer保留了很多内存,我认为至少1000字节,所以对于那个简单的例子来说,最好还是不要使用StringBuffer。当然
现在,我们在内存中有两个字符串“Hello World”和“Hello World!”,但仍然比具有1000字节或更多字节的StringBuffer要好。对吗?我会回答:“当初始化这个静态变量时”
我经历过Java类在需要时被加载。例如,如果从不使用它(例如,从不引用变量或调用函数/构造函数),JVM不会初始化该类
因此,当您调用Runtime.getRuntime()时,类和静态字段都将初始化
您还可以使用带有此代码的静态块对其进行测试
public类MainClass{
公共静态void main(字符串[]args){
System.out.println(“程序启动”);
getRuntime();
System.out.println(“程序结束”);
}
}
公共类运行时{
//这个私人会员什么时候开始??
私有静态运行时currentRuntime=新运行时();
静止的{
System.out.println(“当调用它时,类正在初始化”);
System.out.println(“currentRuntime是否为null?”->“+(currentRuntime==null));
}
公共静态运行时getRuntime(){
System.out.println(“执行getRuntime”);
返回当前运行时;
}
}
这是我在控制台上看到的
program starts
when this is called the class is beeing initialized
is currentRuntime null? -> false
getRuntime is called
programs end
这是什么意思?类运行时(及其字段)在main()启动之前未初始化,但在请求运行时时初始化
另外,当currentRuntime不为null时调用静态块,因此它已经初始化(记住Java是自顶向下的)
因此,它在调用Runtime.getRuntime()时初始化,但在执行之前请