Home  Memory management  Java equivalent to...  const  new  delete  malloc

Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java

What is the Java equivalent of const?

In C++, the const keyword can be used to force a variable or pointer to be read-only. As an example, let's suppose we have a struct declared as follows:

typedef struct Obj {
  int ival;
  struct Obj *next;
} OBJ;

Ordinarily, if we declare a variable of type OBJ or as being a pointer to an OBJ, there's nothing to stop us modifying the object's fields via that variable after declaration. However, if we declare either variable as const, then the fields of the object cannot be modified via that variable:

const OBJ obj1;
const OBJ *obj2;
obj1.ival = 0; <-- NOT ALLOWED!
obj1.next = 0; <-- NOT ALLOWED!
obj2->ival = 0; <-- NOT ALLOWED!
obj2->next = 0; <-- NOT ALLOWED!

Note that const (a) doesn't really give us any guarantee about the modifiability of the actual object, just about whether a particular variable gives read-only access; (b) the read-only guarantee isn't applied recursively to fields inside the referred-to struct or object. So (a) we can create a new variable referring to the same struct that "casts away" the const operator, then use that variable to modify the struct; and (b) we can change obj2->next->next even if we can't change obj2->next. So the following code is allowed:

const OBJ obj1;
const OBJ *obj2;
obj2->next->next = 0;
OBJ *objRef = (OBJ *) obj2;
objRef->next = 0;

Const pointers

A subtlety is that by changing the order of the modifiers, we can create a const pointer. In this case, the contents of the struct can be modified (via this pointer variable), but the actual pointer can't:

OBJ* const obj;
obj->next = 0;   // Allowed
obj = otherPtr;  // Not allowed 

Const member functions

Finally, and perhaps less commonly, const can be used in C++ to indicate that a member function of a class has no side effects on the object it is applied to. (In effect, it is not allowed to modify any of the object's fields.)

const in Java

On the next page, we look at the equivalent of const in Java, showing that in some cases the final keyword provides similar functionality. But we see that in Java, access to object members is controlled by the class itself, so another workaround must be provided for giving read-only access to object members.


Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved.