Why is there no Constant feature in Java?

gmhk picture gmhk · Apr 29, 2010 · Viewed 132.6k times · Source

I was trying to identify the reason behind constants in Java I have learned that Java allows us to declare constants by using final keyword.

My question is why didn't Java introduce a Constant (const) feature. Since many people say it has come from C++, in C++ we have const keyword.

Please share your thoughts.

Answer

Gunslinger47 picture Gunslinger47 · Apr 29, 2010

Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.

Wikipedia offers the following information on the subject:

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.