Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 965
Thomas Johansson Avatar asked Jun 21 '11 13:06

Thomas Johansson


People also ask

Are variables inside a static method static?

Local variables in static methods are just local variables in a static method. They're not static, and they're not special in any way. Static variables are held in memory attached to the corresponding Class objects; any objects referenced by static reference variables just live in the regular heap.

Can static method have static variable in Java?

A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.

Can a variable be declared static in Java?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Can we declare local variable in static method in Java?

In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.


2 Answers

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.

like image 85
Jon Skeet Avatar answered Oct 11 '22 13:10

Jon Skeet


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.

like image 44
Sean Patrick Floyd Avatar answered Oct 11 '22 14:10

Sean Patrick Floyd