Search code examples
c++constantsfinal

Does final keyword in java show varying effects when applied :- 1) on a primitive 2) on an object?


It appears to me as if :-

when final is applied to a primitive it behaves as a pointer to a constant :-

const (type)* ptr

and when final is applied to an obect it behaves as a constant pointer :-

(type)* const ptr


Solution

  • Your first point is a misunderstanding.

    Primitive variables never behave like pointers - the value of a primitive variable is a primitive.
    The value of an object variable is a reference to an object.

    final applies to variables, not to values, and means that you can't assign a new value to the variable.

    If it's a primitive variable, its value remains the same primitive.
    If it's an object variable, the variable always refers to the same, possibly mutable, object.

    So the behaviour is identical.