Why is there no Constant feature in Java?
Solution 1
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.
Solution 2
What does const
mean
First, realize that the semantics of a "const" keyword means different things to different people:
-
read-only reference - Java
final
semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable -
readable-only reference - C
const
pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instance - immutable object - means the instance itself cannot be modified - applies to instance, so any non-const reference would not be allowed or could not be used to modify the instance
- some combination of the the above?
- others?
Why or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070
While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const
include:
- may have confusing semantics that may be misused and/or abused (see the What does
const
mean above) - may duplicate capability otherwise available (e.g. designing an immutable class, using an immutable interface)
- may be feature creep, leading to a need for other semantic changes such as support for passing objects by value
Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const
keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.
Solution 3
const
in C++ does not mean that a value is a constant.
const
in C++ implies that the client of a contract undertakes not to alter its value.
Whether the value of a const
expression changes becomes more evident if you are in an environment which supports thread based concurrency.
As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final
has.
eg:
#include <iostream>
int main ()
{
volatile const int x = 42;
std::cout << x << std::endl;
*const_cast<int*>(&x) = 7;
std::cout << x << std::endl;
return 0;
}
outputs 42 then 7.
Although x
marked as const
, as a non-const alias is created, x
is not a constant. Not every compiler requires volatile
for this behaviour (though every compiler is permitted to inline the constant)
With more complicated systems you get const/non-const aliases without use of const_cast
, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const
merely means that your code can't change it without a cast, not that the value is constant.
Solution 4
This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.
Bloch then describes how to make your classes immutable, by following 5 simple rules:
- Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
- Ensure that the class can’t be extended (this means declaring the class itself as
final
). - Make all fields
final
. - Make all fields
private
. - Ensure exclusive access to any mutable components. (by making defensive copies of the objects)
For more details I highly recommend picking up a copy of the book.
Solution 5
The C++ semantics of const
are very different from Java final
. If the designers had used const
it would have been unnecessarily confusing.
The fact that const
is a reserved word suggests that the designers had ideas for implementing const
, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const
would cause compatibility problems.
Related videos on Youtube
gmhk
Bangalore, India, Dream to Develop a Web Eco System where all Internet users can interact and exchange Ideas. Always work on New innovative Ideas with latest technology
Updated on July 03, 2020Comments
-
gmhk almost 4 years
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 haveconst
keyword.Please share your thoughts.
-
user207421 about 8 yearsThere is a
const
keyword, but there is no underlying feature. Corrected your title and tags accordingly.
-
-
Admin about 14 yearsconst int x = 42; - x is a constant
-
Andy Johnson about 14 years@Neil I think he's talking about objects
-
Admin about 14 years@andy Works the same for objects.
-
Andy Johnson about 14 years@Neil What I meant was: when Pete wrote that const does not mean a value is constant, my understanding was that he was only talking about primitive types. To explain further (and I appreciate that you know this stuff): For a const non-object variable (say an int), the compiler enforces the contract. If I declare it const then it can't be changed. For a object I have to declare as const any member functions that modify the object's internal state. If I don't then its possible to have a const instance of that class that is (internally) mutable. That was my understanding of what he wrote.
-
Pete Kirkham about 14 years@Neil If you have one object or variable aliased by both const and non-const pointers, then the value of the const alias can be changed by the non-const alias. Therefore
const
does not mean a value is constant. It means that the client of a value is constrained not to mutate it. In your example there is no alias, so all users are under the same constraint. This is not the case in general.const
effects the clients, not the value - it says you can't change it, not that it won't change. -
gmhk about 14 years@Bozho, you said better behaviour than Const, what way it is? can you share any example
-
gmhk about 14 yearsI was thinking about the objects
-
Bozho about 14 yearswell, the variable is
static
(not belonging to particular instance) andfinal
- cannot be changed. -
Martin Andersson about 11 yearsConst-correctness is about what the programmer should do, not what they can do. I think you all seem to have got that point. Just wanted to add a couple of cents that could be of interest to the causal reader: Design patterns like the
immutable interface
andimmutable object
is another way (beatable with cast and reflection) to mimic const in Java. "True" const can be done with SealedObject, alas it destroys the use case of our object. -
reinierpost almost 10 yearsJava's
final
is similar, though. -
dom0 over 9 yearsNo it isn't.
final
method for example work completely different from C++const
methods. -
Cygon over 9 yearsOne should note that the outcome of your program is undefined. const_cast is not there to change const variables, it is there to pass const variables to APIs that are not const correct, but also do not modify the value. I think the habit of thinking that something const won't change is a good one because if they do change, that means your program contains hacks that might break at any time depending on the compiler used.
-
Pete Kirkham over 9 years@Cygon in the example it shows you can use a hack to create a non-const alias. But not all non-const aliases are hacks, for example passing
c
andc+1
tostrncpy
will violate any assumption instrncpy
that the source won't change . -
Cygon over 9 years@PeteKirkham Precisely, and because of that passing overlapping memory to
strncpy()
is a hack, too -- it lands you in undefined territory: "The behavior of strncpy is undefined if the strings overlap" (GNU C Library, similar warnings in any other C library). Onlymemmove()
is an exception and needs special sauce in the library implementation to protect against aliasing. -
Zhe Yang almost 9 yearsModifying a born-to-constant value is undefined behavior. Your disk may be already formatted.
-
Pete Kirkham almost 9 years@ZheYang it's an illustration. More realistic issues tends to come up where you have one thread mutating an object which was passed into another as a const reference, and that thread assumes it won't change, but that would mean much longer demonstration code.
-
einpoklum over 8 years+1 just for the second part of your answer. Many many keywords have non-trivial semantics. Is
volatile
so simple to understand? Orfinal
? Meh. -
einpoklum over 8 years@anon is quite wrong to claim that
const
works the same for objects and for fundamental integer types. That's just not true. See the discussion in this SO question for example. -
Tim about 8 years@reinierpost The
final
keyword on properties or variables just ensures that a property or variable is only assigned to once. One could still alter the state of this object by, for example, calling some method with side effects.final
is somewhat similair to stack allocation of C++ in terms of refering to an object rather than a pointer, but that's all it is. This is ofcourse in addition to what dom0 already said. -
Mark K Cowan over 7 years
final
in Java seems to work like C++const
for value types, but more like a C++ non-constT&
for reference types -
Piotr Siupa over 7 yearsCan you provide some example of this, please?
-
user1122069 over 7 yearsclass MYString implements GetString { private final String aaaa; public String getString(); } class MutableString implements GetString { private String aaaa2; public String getString(); public String setString() }
-
SJL about 7 yearsThe claim that it
outputs 42 then 7
is wrong; the behavior is undefined. The key is thatx
was declaredconst
(so, for example, it could be placed in read-only memory). In this example, it would be valid for the compiler to completely ignore the assignment and print 42 twice. Ifx
had been declared withoutconst
and been passed as a const-reference to another function, the const_cast would be legal. -
No-Bugs Hare over 6 yearsconst in C++ is MUCH more flexible than full-scale immutability. In a sense, 'const' can be seen as 'immutable within this particular context'. Example: I have a class that isn't immutable, BUT I want to ensure that it is not modified via certain public APIs. Making an interface (and returning it for that public API) as suggested by Gunslinger47 achieves the same thing in Java, but boy - it IS ugly (and so - it is ignored by most of Java developers, leading to significant unnecessary mess)...
-
David Bradley over 5 yearsfinal is a schizophrenic keyword. While it prevents reassignment, it's also used to expose variables to closures. I might want to prevent reassignment but not expose those variables, but there's no way to do it. It's a rather poorly thought out language feature in my opinion.
-
Sisir over 5 years
final
creates runtime constants whileconst
will create compile time constants. In other words if we declare a fieldfinal
, it can be changed inside the constructor, if declaredstatic final
it can be changed inside astatic initializer block
but if you want that the field shouldn't allowed be changed after declaration, thenconst
will be needed which is currently not available. -
afarley about 5 yearsDownvoted for rumor-based optimization because I heard a rumor that this is an ineffective strategy.
-
hamish almost 5 yearsI removed the rumor from the answer. you can still use static final int to create const style code.
-
afarley almost 5 yearsOk, I have removed my downvote. Maybe some of the other downvotes are about the switch statement (what does it have to do with the rest of your example?)
-
hamish almost 5 yearsin the switch statement I used the cRPM as if it was a const. quite right, considering the above. so yes i have removed the switch.
-
Maarten Bodewes over 4 yearsOTOH, Java was designed to use as few of those non-trivial features as possible. And I'm not saying that they achieved that goal (or that Java hasn't drifted away from that goal). But excluding it for that reason may still have had merit. That there are other complicated things is all the more reason not to introduce more (or you'd end up with the D language).