there is a rule which says:
Names representing constants (final variables) must be all uppercase using underscore to separate words (taken from http://geosoft.no/development/javastyle.html)
that works fine for primitive types like int or strings:
private static final int MAX_COUNT = 10;
But what's about non primitive types? In most cases I've seen the following:
private static final Logger log = Logger.getLogger(MyClass.class);
or in singletons, where instance variable is not in upper case.
The question is what is the right way to declare those types of variables (like log and instance)?
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
2.4 Names representing constants (final variables) must be all uppercase using underscore to separate words. Common practice in the Java development community and also the naming convention used by Oracle for the Java core packages. In general, the use of such constants should be minimized.
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_").
The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.
The names of constants in interface types should be, and
final
variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore"_"
characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants includeMIN_VALUE
,MAX_VALUE
,MIN_RADIX
, andMAX_RADIX
of the classCharacter
.A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
Obscuring involving constant names is rare:
- Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
- Constant names cannot obscure method names, because they are distinguished syntactically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With