How to Create a Static Local Variable in Java

How do I create a static local variable in Java?

You can have a static class variable, which will be preserved across all instances of the class. If that's what you want. If not, use an instance variable, which will only be preserved across method calls on this object.

public class Foo {
static int bar;
//set bar somewhere

public int baz() {
return 3 * bar;
}
}

Java static variables and local variables

The local variable hides the original static field somewhat, but it is not inaccessible:

Test.x

And for non-static fields:

this.x // not in this case

So it is allowed, and in effect one often sees:

public class Pt {
private final int x;
public Pt(int x) {
this.x = x;
}
}

Which prevents the need to introduce some convention (_x, mX).

What is not allowed:

void f() {
int x = 42;
if (true) {
int x = 13; // COMPILER ERROR
...
}
}

As this is bad style, causing confusion.

Why there is no local static variable in Java?

You have found the only solution.

Java dropped a number of complexities from C++, and this was one of them.

Static variables scoped to a function do nasty things to you in concurrency (e.g. strtok is a famously nasty one to use with pthreads, for exactly this reason).

In general, what you want is an object with state. The function in question should then have an object-level variable. Then you can create instances that each maintain state.

Much easier to understand/maintain/etc.

If you truly need to maintain state as a singleton, then static fields are it.

Using a local variable when initializing a static variable

I think they want to avoid reading from the volatile field twice.

  • once to check if it is null
  • once for the return

In their version, they only

  • once read it into a local variable
  • confirm that the local variable is not null
  • return that local variable

The optimization is for the "happy path" that happens incredibly more often than the "initial setup path" that only happens once -- or at most a few times if the method is called concurrently before it has finished the initialization.

Or maybe precaution against a concurrent modification?

There is no such precaution. If you call linePattern concurrently before it has finished setting the static volatile field, the pattern will be created multiple times (but that's fine), different instances will be returned and a random one of those will be chosen to stick around (that's also fine, since they are equivalent).

Any measures to guard against that would only add cost to our "happy path" so should only be done in situations were the instance must really be a singleton for some reason.

Java - local variables in static method

A field cannot be referred by a static method because it belongs to an Instance of a Class and therefore it is out of the static method's scope.

Local variables are never static. By "local" variables, it is understood variables declared and used in a code block, whether that code block be a static initializer, class initializer or method/constructor body. The scope of such variables is of course determined by the code block they are declared in.

Not to be mixed with variables declared in classes (fields), whether they be instance variables (non static; one per instance) or class variables (static; one per class).

Should this variable be local or static?

This is entirely your choice. Your program will function the same way. The only difference is at the memory and processing power level.

Will you call many methods that use randomNumber in a row? Then don't destroy it and let it be an instance variable.

Do you plan on calling such a function every once in a while? Then don't keep the object in memory, let it be vreated only when you need it and destroy it afterwards (use it as a local variable).

How to mock local variable in a static method of a private java class?

You should add ActivationDBManager to @PrepareForTest, because you are manipulating its bytecode (using whenNew).

Java instance variable of a static method

Firstly, the term instance variable is not accurate, I am assuming that you are asking about local variable such as a and b in the example below:

void method(int a) {
int b = 3;
}

In Java, only primitives and references are stored on stack, objects are stored in heap when they are constructed. Stack will be cleaned as soon as the scope ends, heap is cleaned by garbage collector.

Here is an example:

public class Main  {

static A a = new A();

static void method() {
int b = 2;
C c = new C();
}

}

The first time your code refers to Main, class loader will load the class and initialize all its static fields - object new A() will go into heap. Nothing more happens here, method method could as well not exist.

When you call method method, it will add value 2 on the stack, then it will add reference c on the stack which will be pointing to the object new C() in the heap.

When method exists, 2 and c are removed from the stack (there is actually no removal, but the top of the stack is changed to two positions below so these two values will be overriden whenever something else comes onto stack), while new C() will remain in heap until garbage collector triggers. It's likely that it will be garbage collected immediately as GC may detect that there are no more references to this object.

Are local variables in static methods also static?

The answer to most of your questions is "the same as any other variable."

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.

When you pass a static variable to a method as an argument... absolutely nothing interesting happens.

Regarding the scenario in your code:

  1. Imagine that you have a toy balloon on a string (the balloon is your array object, and the string is the reference to it declared in A().)
  2. Now you tie another string on to the balloon and hand that string to a friend (that's exactly what happens when you call the changeX() method: the string is the parameter of the method, and it points to the same object.)
  3. Next, your friend pulls in the string, takes a black marker and draws a face on the balloon (this is like the changeX() method modifying the array).
  4. Then your friend unties his string, leaving just your string attached to the balloon (the method returns, and the local variable in changeX() goes out of scope.)
  5. Finally you reel in the string and look at the balloon: of course, you see the face (your A() routine sees the changed array.)

It's really as simple as that!



Related Topics



Leave a reply



Submit