In java, if a variable is immutable and final, then should it be a static class variable?
I ask because it seems futile to create a new object every time an instance of a class uses it (since it is always the same).
Example:
Variables created in the method every time it is called:
public class SomeClass {
public void someMethod() {
final String someRegex = "\\d+";
final Pattern somePattern = Pattern.compile(someRegex);
...
}
}
Variables created once:
public class SomeClass {
private final static String someRegex = "\\d+";
private final static Pattern somePattern = Pattern.compile(someRegex);
public void someMethod() {
...
}
}
Is it always preferable to use the latest code?
This answer seems to indicate that it is preferable to use the last code: How to initialize a String array of length 0 in Java?
source
share