I want to write perfect Java code, so please let me ask this question.
I want to use a never-changing String variable in my method like this:
1. String STR4SEARCH_START = "Abc";
And I could define it just in my method, and because it doesn’t need to change, I could also define it in my class like this:
2. private final String STR4SEARCH_START = "Abc";
3. private static final String STR4SEARCH_START = "Abc";
4. public final String STR4SEARCH_START = "Abc";
5. public static final String STR4SEARCH_START = "Abc";
Here is my question: from way1-way5, which one is the best, and could you please explain why?
Thank you very much.
It depends. If you want others (outside of your class) to be able to view it, then use
publicnotprivate, and vice versa. Other than that, I would certainly usestatic finalbecause you essentially want to define an unchanging constant, as you said.staticbecause each instantiation of your class will not require a different value, andfinalbecause its value will not change.