Search code examples
javaconstants

Method Specific Constants in Java


Is it possible to have a constant variable that is local only to a specific method? It seems unnecessary to put it at the class level when it is only used in one method. Using the "final" modifier in the method will prevent the variable from being modified after it is initialized, but it will be re-initialized every time the method is called, even when it is unnecessary. Is there a way to make it static? For example, in the following code, "calculating" is printed every time the doStuff method is called:

public void doStuff() { 
    final int myVar = getNum();
    ...
}

public int getNum() {
    System.out.println("calculating");
    return 2;
}

Can "myVar" be initialized once, say, when the class is loaded without being outside of the method?

This is mostly out of curiosity. Is this something that is ever done or suggested?


Solution

  • Methods in Java cannot have static variables at this time.

    Is this something that is ever done or suggested?

    Some other languages (C, C++) have this. It does provide additional encapsulation of data. For example, in C++ it is the canonical lazy-instantiated singleton:

    Singleton const* Singleton::instance() {
        const static Singleton instance;
        return &instance;
    }
    

    I'm not aware it is a proposed feature for Java.