0

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

7
  • 1
    Yes. You should prefer the final static option. Commented Sep 30, 2016 at 13:08
  • 1
    it depends of want you want to do, final static could involve an issue in mutli-threading environment. Commented Sep 30, 2016 at 13:11
  • What does the variable mean? How is it initialized? Is it logically method-call-specific state, or type-wide state? Commented Sep 30, 2016 at 13:15
  • @JonSkeet it is a List of few constants, initialized using Arrays.asList(...) Commented Sep 30, 2016 at 13:19
  • If these are constants, I think you have answered your question. Constants should be static final. So should be this list. However, don't forget to make it immutable (Collections.unmodifiableList(...)). Commented Sep 30, 2016 at 13:27

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

If this requires work to initialize, you absolutely shouldn't "trust the compiler to make any optimizations". There could be side-effects involved, for example.
I think in that case I'd use an inner class.
Without knowing anything more than the scant information in the question, I'd prefer not to offer an opinion. There's a lot of context we don't know here.
0

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.

1 Comment

you should explain more, if you can use some examples, this can not be an answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.