在 C 中初始化静态变量时,根据功能,内存分配仅发生一次。因此,在同一函数中递增变量时,它会在下一次函数调用期间保留递增的值。但是在Java中同样测试失败,给出编译错误,指定,static不能使用。
尝试用 Java 和 C 编写代码并获得不同的结果。 C 执行,而 Java 提供编译错误。
C 代码:
#include<stdio.h>
void func()
{
static int k=0;
printf("%d ",++k);
}
int main()
{
int i;
for(i=0;i<5;i++)
func();
return 0;
}
Java 代码:
public class Test
{
public static void main(String[] args)
{
Test obj=new Test();
for(int i=1;i<6;i++)
obj.increment();
}
void increment()
{
static int i=0;
System.out.println(i++);
}
}
C输出:
1 2个 3个 4个 5
Java 编译时错误:
java: 表达式的非法开始
最佳答案
在 Java 中没有 static
局部变量 - 唯一可以放置 static
关键字的地方是:
字段
public class Test {
static Object staticField;
// ...
方法
public class Test {
static Object getStaticField() {
// ...
}
// ...
内部类
public class Test {
static class InnerTest {
// ...
}
// ...
静态初始化 block
public class Test {
static Object staticField;
static { // this will be called before constructor
staticField = new Object();
// ...
导入
import static java.lang.Math.PI; // now you can use PI without 'Math.'
关于java - 静态变量在Java编译时出错,在C中一次性内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57467414/