javaswiftvariablesfinallet

Why isn't Java variable declared as `final` more often? Compare to let keyword in swift


In swift, it is recommended to declare a variable with let keyword if the variable does not change after initialisation. I see a lot of variables declared as let.

In java, I think the keyword final can serve the same purpose. But from my limited experience, I only see people declaring variables as final in rare circumstance e.g. PI.

Why isn't Java variable declared as final more often? Is there something I'm missing?


Solution

  • see In Java, should I use “final” for parameters and locals even when I don't have to?

    Basically, for fields, it is useful and also changes their concurrency properties. see Java concurrency: is final field (initialized in constructor) thread-safe?

    However, for local variables and parameters, final's value is less clear. It has some semantic value, but on the other hand, it can also be noise to have

    public void foo (final int x, final int y){
        try{
            final int z = x+y;
        }
        catch (final Exception z){
            final String message = "";
            throw new RuntimeException(message);
        }
    }
    

    compared to

    public void foo (int x, int y){
        try{
            int z = x+y;
        }
        catch ( Exception z){
            String message = "";
            throw new RuntimeException(message);
        }
    }
    

    If you have short methods (which you usually should have), then it is obvious anyway that the variables are not being changed.

    Therefore, some developers prefer using final for its semantic value, while others prefer not to use it because of its verbosity.