In java, if a variable is immutable and final then should it be a static class variable?
I ask because it seems wasteful to create a new object every time an instance of the class uses it (since it is always the same anyway).
Example:
Variables created in the method each 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 latter code?
This answer seems to indicate that it is preferable to use the latter code: How can I initialize a String array with length 0 in Java?