3

If name is declared final, why i can still call name.append and the output is: shreya? I thought final variables cannot be changed once a value is assigned?

public class Test1 {

    final static StringBuilder name = new StringBuilder("sh");
    public static void main(String[] args) {

        name.append("reya");
        System.out.println(name);
    }

}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
OPK
  • 4,120
  • 6
  • 36
  • 66
  • You are not changing the value of this variable with name.append("reya"), the values of this variable is a memory position (new StringBuider("sh")) . – Gödel77 Jan 08 '15 at 22:55
  • You can't change the `final` variable `name`, you can only change the object that variable points to. – Peter Lawrey Jan 08 '15 at 23:00

2 Answers2

13

final refers to not being able to change the reference, e.g. you cannot say name = new StringBuilder(). It does not make the referenced object immutable.

Immutability is a property of a class. An object of a mutable type is always mutable.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
5

You have to start making the distinction between variables, values (reference values and primitive values) and objects and primitives.

A variable is container for a value. That value is either a reference value (for objects) or a primitive value.

You cannot use the assignment operator to assign a new value to a final variable once it has been initialized with its original value.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724