开发者

In Java, are variables declared inside static methods themselves static?

Assume the 开发者_高级运维following:

private static boolean A()
{
  int parsedUntil = 0;
  ...
  ...
  ...
}

Is parsedUntil considered to be a static variable? I noticed that I can't declare it as static inside this static function.

Follow-up question: I read that a static variable will only be initialized once. Does that mean the first time I call function A() the value will be set to zero, but every other time I call A(), that row is omitted?


No, it's not a static variable. It's a local variable. Any variable declared in a method is a local variable. If you want a static variable, you have to declare it outside the method:

private static int parsedUntil = 0;

There's no way of declaring a static variable which can only be used within a single method.


no, A() is a static method, and parsedUntil is a local variable inside A.

Modifiers like static are not valid in local variables (only final is permitted afaik)

Follow-up question: I read that a static variable will only be initialized once.

true

Does that mean the first time I call function A() the value will be set to zero, but every other time I call A(), that row is omitted?

since parsedUntil is not a static field, but a local variable in a static method, this is not the case.


static variables cannot be declared locally inside methods - they can only be members of a class, and they get initialised when the class is loaded.


Java does not have static local variables like C or C++ does, so you can never have static int parsedUtil = 0;.

So no, parsedUtil is not in any sense "static". Its value is initialised to 0 every time the method is executed.


No it's not C.

parsedUntil is not static. It's just a local variable. You cannot declare static variable inside the method.

Regarding second question - static variables can be assigned as many times as you want. You cannot reassign only final variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜