02 July 2010

final varaibles in Java and its relation to const in C

Hi folks,

Java uses the keyword `final` with variables in indicate that this variable is a constant.

ex1:

final int x = 10;

The above line means x is a constant of type `int` that its value cannot be altered.

ex2:
final Employee e = new Employee("Ahmed");

The above line means e is a constant of type `Employee` that its value cannot be altered.

So, the following line will not compile:
e = new Employee("Mohammed"); // compile error

But the following line will successfully compile:
e.setName("Ali");

Let's derive something:
For primitive, final is a keyword that ensure that the value of the primitive will never change.
For references, final is a keyword that ensure that the variable name cannot be reassigned to any other objects any more.

But, In C:
When we say:

//we define a pointer of type x, that its value cannot change.
int y=100;
const int* x = NULL;
*x = 20; // will not compile
x = &y; // will compile

but, when we say:

int y=100;
int* const x = malloc(sizeof(int*));
*x = 20; // will compile
x = &y; // will not compile
we define a pointer of type x, which that address its points to cannot change.

Conclusion:
So, We can say that, `final` in java with reference types act the same behavior of constant pointers in C (not value pointers). i.e. we cannot make it to refer (point) to another object, but we can change it's value.

No comments: