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?
No definitely not.
class MyIntegerContainer{
private final int x;
public MyIntegerContainer(int x){
this.x = x;
}
}
If you made immutable, final x
static, then all instances of MyIntegerContainer
would share the same value of x
which would not make for a very good data container.
Ultimately it depends on what you're doing with those variables.
If the variable only ever has a lifecycle inside of that specific method - that is, nothing else will ever need to see it or use those values - then declaring them inside of the method is appropriate and correct. Making it more visible than it needs to only adds to confusion for future maintainers (including yourself).
If the variable has a lifecycle outside of the class, it might make sense to declare it static
. This is particularly true in the case of constants or variables that don't store any state themselves.
If it isn't a constant or it doesn't have any purpose outside of the class, then keep it non-static and private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With