Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constant variable, naming convention [duplicate]

Is there any naming convention for java constant variable?
Normally we use variables with names containing uppercase letters and underscores(_).

For example:

public final class DeclareConstant {      public static final String CONSTANT_STRING = "some constant";      public static final int CONSTANT_INTEGER = 5;  } 
like image 218
Shreyos Adikari Avatar asked Sep 20 '12 19:09

Shreyos Adikari


People also ask

What is the naming convention for constants in Java?

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

What are the rules for naming of constants?

Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.

How do you declare a constant variable in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.

Should all final variables be capitalized?

If it's private or protected then it should be all lowercase. If it's public or package then it should be all uppercase.


2 Answers

Yes. That is it. It is often used for enum as well.

The only common exception is for logging where you might see

private static final Logger log = Logger.getLogger(getClass().getName()); 

but I prefer LOG

I often write this as UPPER_CASE, but I also write TitleCase for classes and camelCase for variables and methods.

like image 81
Peter Lawrey Avatar answered Oct 11 '22 07:10

Peter Lawrey


That is right. According to Sun:

Scroll to the bottom see constants

Constants

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;

like image 39
zw324 Avatar answered Oct 11 '22 07:10

zw324