Hacker News new | ask | show | jobs
by asn0 1879 days ago
Since Java 10:

  var mutableVar = "Foo"
  final var immutableVar = "Bar"
2 comments

This is not immutability, final only prevents re-assignment, not mutation:

    final ArrayList<String> foo = new ArrayList<>();
    foo.add("Foo"); // Compiles and runs - this is mutation
    foo = new ArrayList<>(); // Compiler error - this is re-assignment
In your example, both Strings are immutable, since Java Strings are always immutable.
The variable is immutable.
Final has been in Java for a lot longer, but you're also missing the point. Immutability should be the default, or at least not a secondary citizen to the dangerous and often unnecessary mutability.
Yes, I still remember how in Ceylon they just did "value x = bla" and the variable was immutable by default. If you wanted to actually make it mutable you had to write it out as "variable Type x = a" to make it stand out and be really annoying to have mutable variables.
Which is the road taken by record classes and the upcoming primitives.