Programming Tips - Java `final` vs C++ `const`

Date: 2023aug28 Language: mixed Q. Java `final` vs C++ `const` A. They are similar but `const` is more strict. The first assignment `final` means a variable can only be assigned a value once. `const` means a variable can only be assigned a value when its declared. Example valid Java:
class Example { public static void main(String[] args) { final String hello; hello = "hello"; // OK System.out.println(hello); } }
Example invalid C++:
#include <string> #include <iostream> int main() { const std::string hello; hello = "hello"; // Error - cannot assign to const std::cout << hello; }
Subsequent changes `final` only forbids changes to the variable but its contents can change `const` forbids changes to the variable's contents Example valid Java:
class Example { public static void main(String[] args) { class MyClass { int a = 1; } final foo = new MyClass(); foo.a = 4; // Changing a `final` member is allowed! System.out.println(foo.a); // Prints '4' } }
Example invalid C++:
#include <iostream> class MyClass { public: int a = 1; }; int main() { const MyClass foo; foo.a = 4; // Error - cannot change a `const` member std::cout << foo.a; }