Search code examples
javaimmutability

Constant Object vs Immutable Object


Can I use the term "Constant Object" in the place of the term "Immutable Object"? Though I get the feeling that Immutable for an Object is what Constant is for a variable, I am not sure if this terminology is accepted. Please help me understand.


Solution

  • In fact, in Java the term constant has no defined meaning. It occurs in the JLS only in the larger term compile time constant expression, which is an expression which can (and must) be calculated by the compiler instead of at runtime. (And the keyword const is reserved to allow compilers to give better error messages.)

    In Java, we instead use the term final to refer to variables (whether class, object or local ones) who can't be changed, and immutable when we refer to objects who can't change. Both can be used when speaking about a variable x - the first then means the variable itself (meaning it can't be switched to another object), the second means the object behind the variable. Thus here the two meanings are orthogonal, and are often combined to create a "true constant".