Saturday, July 7, 2007

Comparisons of C++ and Java (VI): Constant Modifier

Constant modifier is const in C++ and final in Java. However, const and final are not equivalent at any situations (In C++, we can also define a constant by using the #define preprocessor directive, but I am not going to discuss it here)


1. For primitive data type,
const and final have the same meaning, that is the variable can only be assigned once and its value cannot be changed. For instance:


const int i = 10;

in C++ is equivalent to


final int i = 10;

in Java. It illegal to modify the variable after its initialization in both cases.


2. However,
for non-primitive data type (reference data type in Java, structured data types and address types in C++), const and final are different.

Let take a look at some examples. In Java, this piece of code is perfectly legal:


final int[] ary = {1, 2, 3, 4, 5};
ary[4] = 6; //legal

However in C++, this piece of code:


const int ary[] = {1, 2, 3, 4, 5};
ary[4] = 6; // illegal. compilation-time error

will generate compilation-time error:

Error: assignment of read-only location.


3. Why const and final are different regarding to non-primitive datatype?

For mathematics, a constant is a value that never changes, thereby remaining a fixed value. So in C++, a constant is a REAL constant. const is infectious. A const modifier ensures that the object is immutable (It is called Const Correctness in C++). When const keyword is involved when used with pointers or references, we can't modify what the pointer points to or the reference refers to.

While, there is no such const correctness in Java. A final modifier just tells the compiler that the reference to the object cannot be re-assigned, but nothing about its content. A final modifier can never change the immutability of an object. A constant in Java is NOT a real constant. const is a reserved keyword in Java. We may expect the implementation of Const Correctness in Java in the future.


No comments: