Is there any reason to do this:
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
instead of this?
private static Logger logger = LoggerFactory.getLogger(Main.class);
I don’t undertstand what the syntactical benefit is of one over the other. Both seem to work fine.
It is a convention inherited from the C/C++ world that constants are named all uppercase. Since in Java, the closest equivalent of constant is
static final, these members are often named similarly.In this case, the distinction may not be so important, since logger objects are semantically not constants. Nevertheless, it is still recommended to declare them
staticto ensure you have a single instance per class, and you may want to declare themfinalto ensure that the reference to the object can’t be changed later (and to communicate this fact to readers of your code).Update to @Moncader’s comment:
staticis equivalent to C++ (class)static– just as well as it does not make much sense in C++ to declare your constants as non-static, it does not make sense in Java either.finalis not a direct equivalent of C++const. It means that the reference in question can not be changed. However, it does not prevent changing the object referred to! So it only works as const if it protects a primitive value (e.g.int) or a reference to an immutable object (e.g.String). To stay with our current topic, considerprivate static final Logger logger = LoggerFactory.getLogger(Main.class);
…
logger.setLevel(Level.INFO);
logger.addAppender(…);
logger.setAdditivity(false);
All of these calls are obviously changing the state of the logger, even though it is declared
final. That’s what I meant above by stating that logger objects are semantically not constants.