Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should immutable, final variables always be static? [duplicate]

Tags:

java

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?

like image 791
theyuv Avatar asked Mar 06 '23 16:03

theyuv


2 Answers

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.

like image 169
Blake Avatar answered Mar 09 '23 05:03

Blake


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.

like image 31
Makoto Avatar answered Mar 09 '23 05:03

Makoto