Jasir
Jasir

Reputation: 697

Should I prefer final static variable inside class or final variable inside a static method

Provided the final variable is used only inside one static method, should I declare it as final static member in class, or final variable in the static method.

If it is declared inside method, will it be initialized each time the function is called. (function is invoked a lot of times)

EDIT: The Variable is a List initialized using Arrays.asList(...) function

Upvotes: 0

Views: 95

Answers (3)

kamalakar
kamalakar

Reputation: 1

Yes, final static can be used. The element will initialize only once: at time of class loading. You can use this any number of times.

Upvotes: 0

Lucas Oliveira
Lucas Oliveira

Reputation: 3477

If it is declared inside method, will it be initialized each time the function is called. (function is invoked a lot of times)

Yes. If you declare your variable inside the method, it will invoke Arrays.asList(...) each time the method is invoked.

If your variable has a costly initialization and/or the method is invoked a lot of times you should declare it as a private static final field.

Upvotes: 1

user6409912
user6409912

Reputation:

Ideally you'd want it to be a static final in the method itself. But Java does not support that. (C++ does by the way).

Unless the variable is a reference to an object that has startup overhead, I'd keep it as local as possible and write final in the method, rather than pollute the class namespace with a final static that's only used in one function. I'd trust the compiler to make any optimisations. Alternatively, create an inner class and declare it there.

Upvotes: 0

Related Questions