If I have a string constant that is used only by a single method, is it better to make it static final
:
private static final String MY_CONST = "something";
or simply define it at the top of the method:
private void myMethod() {
final String myConst = "something";
// ... code that uses myConst a lot
}
or another way?
It doesn't matter either way, the only thing that matters is the readability to you. A good question to ask yourself is: which is easier for you to read and what makes more sense for you? Personally for me, I would use the second one, because it is only used in one method. However, if you are going to be changing the value a lot, then I would use the first one. But ultimately, it is totally up to you as the programmer and what makes more sense in your mind. I hope this gives you a better understanding.
I would use it directly in the method. Not only me actually, if we browse thru JDK code we will see lots of examle when many literals are used in a class and no one static final
field is declared. Take a look at java.io.DataInputStream
. JDK typically uses constant fields if a constant is supposed to be used in other classes, that is public static final
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.