If immutable final variables are always static?

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?

+4
source share
2 answers

No, definitely not.

class MyIntegerContainer{
    private final int x;
    public MyIntegerContainer(int x){
        this.x = x;
    }
}

x, MyIntegerContainer x, .

+6

, .

- - , . , , ( ).

, static. , .

- , .

+1

Source: https://habr.com/ru/post/1694868/


All Articles