Why does Java allow the use of "end" within methods and functions?

I was looking at one of the questions and I got the doubt that the title says.

Why is the final keyword allowed inside methods and functions?

 4
Author: Comunidad, 2016-05-13

2 answers

The word final applied to variables means that the value of the variable cannot be modified. This allows the compiler to ensure that the variable is only initialized in its declaration (in the case of class attributes, the variable must be assigned when declared or in the class constructor). In case the variable is rebooted, this will throw a build error.

For variables of primitive type, this is simple from understand:

final int i = 5;
i = 7; //error de compilación aquí

For object type variables, consider that the value of the variable is a reference and not its state. Here is an example:

public class MiEntidad {
    int id;
    String nombre;
}

//asignando una referencia como valor a la variable
final MiEntidad miEntidad = new MiEntidad();
//aquí se modifica el estado interno de dicha referencia
//pero la referencia mantiene su mismo valor
miEntidad.id = 1; //esto cambia el estado de l
miEntidad.nombre = "Luiggi";
//aquí se intenta asignar una nueva referencia a la variable
//por ende, ocurre un error de compilación
miEntidad = new MiEntidad();

Since a variable is declared as final, this assures the compiler that the variable cannot change its value. This is very useful when you have variables local to a method and these need to be used within a class local to the method (commonly called anonymous classes) since this class cannot assign values to variables that do not belong to the class or to local variables. Here is an example:

public void metodoX() {
    //si remueves la palabra final, saldrá un error de compilación
    //en la clase interna
    final int tope = 10;
    Thread t = new Thread( () -> {
        //esta es una clase interna local al método metodoX
        //que implementa la interfaz Runnable
        //y hace uso de la variable externa "tope"
        //puesto que "tope" es ajena a la clase interna y
        //no pertenece a la clase donde se encuentra metodoX
        //la variable necesita ser declarada como final
        for (int i = 1; i <= tope; i++) {
            System.out.println(String.format("Hola %d", i));
        }
    });
    t.start();
}

final it has other uses:

  • Declare a class as final. This makes the class cannot be extended. Example:

    public final class NoMeHereden {
    }
    
    //error de compilación
    //puesto que la clase NoMeHereden está declarada como final
    public class YoQuieroHeredarDe extends NoMeHereden {
    }
    
  • Declare a method as final: the method cannot be overridden. Example:

    public class HeredenDeMi {
        public final void peroNoSobreescribanEsto() {
        }
    }
    
    public class YoHeredoDe extends HeredenDeMi {
        //error de compilación
        //el método está declarado como final
        //no puede ser sobreescrito
        @Override
        public void peroNoSobreescribanEsto() {
        }
    }
    
  • Define a class attribute as static final: the attribute has a value constant at compile and run time. This is mainly used to define application-level constant variables. Example:

    public class MisConstantes {
        public static final int CERO = 0;
        public static final String DELIMITADOR_BASE = "_";
        //como es una constante, se debe asegurar que la variable
        //y su estado no puedan ser modificados en tiempo de
        //compilación
        public static final List<String> EXTENSIONES_ACEPTADAS =
            Collections.unmodifiableList(Arrays.asList("txt", "pdf", "csv"));
    }
    

Additional: attributes defined in an interface are always declared as, that is, they are constants.

More official information (from the Java Language Specification) about it:

 7
Author: , 2016-05-13 20:36:59

final it has several uses, within methods it is not only important to indicate that the variable cannot be modified... as I already explain @LuiggiMendoza, it is also mandatory when you want to use one of these variables in an anonymous class..

Ex:

int variable = 3;

Thread t = new Thread() { // clase anonima
    public void run() {
        System.out.println(variable); // <-- error de compilacion
    }
};   
t.start(); 

Now if you put the final modifier on

final int variable = 3;

Thread t = new Thread() { // clase anonima
    public void run() {
        System.out.println(variable); // OK
    }
};   
t.start(); 
 3
Author: rnrneverdies, 2016-05-13 20:27:51