Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use upper-case naming to declare java constant variables?

My question: Should names of constant Java variables (within methods) be upper-case?

I've always been under the impression that

a) if a variable is never going to change, it should be declared final (to show/enforce that it won't change) b) it should be named in upper-case

However, I've noticed in eclipse, when changing a variable (within a method) to be final/constant, and subsequently refactoring/renaming it to something like below:

final int NODE_COUNT = 3;

I get the following warning:

This name is discouraged. According to convention, names of local variables should start with a lowercase letter.

Which makes me wonder if the upper-case rule doesn't apply in this instance (i.e. final variable within a method).

like image 938
Jonny Avatar asked Jun 11 '12 10:06

Jonny


People also ask

Should constants be capitalized in Java?

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

Should const variables be uppercase?

"Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters." According to MDN: NOTE: Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters."

What Java naming convention should we used in constant variables?

Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.

What is the proper way of declaring a constant in a method 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.


2 Answers

Within methods you don't have constants, you just have local variables, that can be final. So using normal camelCase starting with lowercase is perfectly suiting there.

like image 110
dantuch Avatar answered Nov 09 '22 09:11

dantuch


Class constants should also be static (making them class-level instead of instance-level), in which case Eclipse will not warn you about using Uppercase.

Method constants should have identifiers starting with a lower-case letter, though, so I agree with your conclusion.

like image 25
ᅙᄉᅙ Avatar answered Nov 09 '22 11:11

ᅙᄉᅙ