Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String constant vs variable in a Java method

Unchangeable, constant values should be stored in constants rather than variables for both safer and cleaner code.

The latter doesn't apply to all cases of unchangeable values though: There's the following method that is only called once, on initialising the app that uses the same value of a String twice. The String is only referenced and used inside the method.

My question is: What's the best way of variable/constant definition? Being a simple String in a large application, performance and memory can be neglected, it's more about readability and maintenance.

Is it as variable inside the method:

protected void init() {
    final String thestring = "thevalue";

    methodA(thestring);
    methodB(thestring);
}

or is it as constant on class level (although only used in the method):

private static final String THESTRING = "thevalue";

protected void init() {

    methodA(THESTRING);
    methodB(THESTRING);
}

or a third, better solution? Please also take into consideration that there can be more, similar methods in the same class.

like image 602
msp Avatar asked Jul 23 '26 08:07

msp


1 Answers

For me the best solution is to use variable inside the method - because it's internal variable. So other methods shouldn't see it. Consider the encapsulation and clean code, when you try to move this variable on class level you will get a long list of class variables.

Another thing is memory. After method is executed the variables are destroyed. When you define it as a static it will be in your memory all the time.

like image 114
KirkoR Avatar answered Jul 27 '26 12:07

KirkoR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!