Camander
Camander

Reputation: 147

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?

Upvotes: 2

Views: 7509

Answers (5)

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

This is possible since Java 16 using local classes with static fields:

private static void doStuff() {
    class Holder {
        static final int myVar = getNum(); // Will be initialized once

        private static int getNum() {
            ...
        }
    }

    // Use Holder.myVar
}

Upvotes: 0

TechTrip
TechTrip

Reputation: 4537

Actually you only accomplish the single instantiation by having the variable initialized outside the method. Otherwise as other people have noted it's not possible to have the static var local to the method.

public class Example {

    public static final int myVar2 = getNum();

    public void doStuff() { 
        System.out.println("In doStuff: myVar = " + myVar2);
    }

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

    public static void main(String[] args) {
        Example ex = new Example();

        for (int i = 0; i < 5; i++){
            ex.doStuff();
        }
    }
}

The output from such a construct is as follows.

calculating In doStuff: myVar = 2 In doStuff: myVar = 2 In doStuff: myVar = 2 In doStuff: myVar = 2 In doStuff: myVar = 2

As you can see it accomplish the static instantiation.

Upvotes: 0

Radiodef
Radiodef

Reputation: 37845

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.

Upvotes: 1

mkobit
mkobit

Reputation: 47259

There is no way of declaring a static variable which can only be used within a single method. It is not part of the Java syntax.

You could do this at your class level with final static modifiers. It will be initialized to a static constant on the class and since it is final, cannot be changed once set:

public class MyClass {
    private static final int myVar = 2;
    ...
}

From Oracle's documentation

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

Upvotes: 0

hfontanez
hfontanez

Reputation: 6168

"Is it possible to have a constant variable that is local only to a specific method?" First, constant variable is a commonly used term, but it is an oxymoron. Something constant cannot change, and a variable has the ability to change. A constant field or constant data member might be more appropriate terms. The question then becomes, why do you need a constant inside a method? After all, even if you make the constant field public, it will not change, so its scope becomes a bit irrelevant.

In practice, constant fields are often made static (not always). Going back to your question, can it be done? The following is valid code:

public class ConstantDemo
{
    public static void main(String[] args)
    {
        ConstantDemo demo = new ConstantDemo();        
        for (int i = 1; i <=12; i++)
            System.out.println("7 times " + i + " equals " + demo.timesSeven(i));
    }

    public int timesSeven(int number)
    {
        final int x = 7;
        return number * x;
    }
}

The question is, what do you really accomplish by limiting the scope of this constant field? As Radiodef suggested, methods cannot have static fields declared inside (in Java).

Upvotes: 0

Related Questions