3

I am using NetBeans IDE and before Java, I was a C++ programmer. From C++, what I learn is that constant variable names should contain only uppercase letters. I think most programming languages suggest that constant variables should only contain uppercase letters with underscores to separate words.

My IDE, NetBeans, only warns me about the convention when I try to declare a static member variable with lowercase letters. It's okay if the variable is final, but non-static.

final int mem1 = 90; // no warning
static final int mem2 = 90; // warning

Shouldn't the programmer be forced to use uppercase letters for naming any kind of (static, non-static) constant variables?

user207421
  • 305,947
  • 44
  • 307
  • 483
  • it´s a naming convention. You are right that it should be followed for readability, but i don´t think it will ever be enforced nor should it be enforced. – SomeJavaGuy Jul 26 '16 at 05:15
  • Because naming conventions are not part of the Java Language Specification. – user207421 Jul 26 '16 at 05:16
  • 1
    A non-static `final` is not a real constant. It could also be initalized in the constructor, based on some runtime calculated values. See also http://stackoverflow.com/questions/10844268/difference-between-final-variables-vs-static-final-variables – Andreas Fester Jul 26 '16 at 05:16
  • 3
    Non-static final variables aren't really constants. They can be different for each instance of the class. – Arjan Jul 26 '16 at 05:16

2 Answers2

8

final doesn't make a value a constant, it simply means that the field's value can only be assigned once.

Here's an example of a non-constant final field:

public final class IntHolder {
  private final int value;

  public IntHolder(int value) {
    this.value = value;
  }

  public int get() {
    return value;
  }
}

Here, the value field is clearly different for each instance of IntHolder, so it isn't a constant. Naming the field like a constant would just lead to confusion.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
4

Only constants should be in Uppercase. However it may depend upon the programmer as how he follows the convention. Some also likes to start constants with an '_' followed by the name in lowercase. Moreover, there is no need to put such a check in compiler as it may depend from the view of programmer.

Abbas Kararawala
  • 1,254
  • 12
  • 19