11

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).

Jonny
  • 3,807
  • 8
  • 31
  • 48
  • 1
    sorry to be flippant but does anybody else find the phrase "constant variables" amusing? – PeteH Jul 10 '12 at 13:22
  • 2
    Upon re-reading it I realise that this is an oxymoron, and should probably be final variables(???), though unless I'm mistaken, once a final variable has been declared, it _is_ final, and so at that point becomes non-variable too, again making "final variable" an oxymoron. Is there another way to describe this? – Jonny Jul 11 '12 at 08:34
  • 1
    +1 jonny, please don't think about this too hard! – PeteH Jul 11 '12 at 10:07

2 Answers2

7

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.

dantuch
  • 9,123
  • 6
  • 45
  • 68
2

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.

P Varga
  • 19,174
  • 12
  • 70
  • 108
  • Thanks, though within a method when I add 'static', I get an 'illegal modifier for parameter NODE_COUNT; only final is permitted' error, so assumed that I couldn't used static within a method. – Jonny Jun 11 '12 at 10:31
  • @jonny you can't add `static` modifier to variable inside any method (doesn't matter if it's static or not). Method is ment to be dinamic - you have your logic there, so its part can't be defined as static.... however of cource you can use static fileds of your class, those are constants. – dantuch Jun 11 '12 at 10:34