Final local variable in inner class in Java 8

2

There was a change between Java versions 7 and 8. Where in Java 7 for a local variable to be used within a inner class it should be declared final . Now compiling with Java 8, this local variable is no longer required to be declared final.

Since Inner Classes needed to access local variables, they would have to be copied to another memory region in order to be accessible by it, which could generate multiple copies of the same variable and run the risk of having inconsistent data. What led to this change in Java 8, or is my whole understanding wrong?

Java Example 7:

public void msgAsync(final String msg){
   java.awt.EventQueue.invokeLater(new Runnable() {
       @Override
       public void run() {
           jText.setText(msg);
       }
   });
}

Java Example 8:

public void msgAsync(String msg){
   java.awt.EventQueue.invokeLater(new Runnable() {
       @Override
       public void run() {
           jText.setText(msg);
       }
   });
}

Both code snippets compile in their respective versions, but note the use of the final modifier being used only in Java 7.

    
asked by anonymous 02.06.2017 / 14:07

1 answer

4

Try to make a change in msg and see if it compiles.

Java 8 decided to infer final if there are no changes in the variable, so you do not have to be explicit, but deep down even 8% with% is msg Java and still requires it to be, the difference is that now the compiler knows if it is even without being written.

The variable is effectively final .

    
02.06.2017 / 14:34