Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between final and effectively final

I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous class they must be final in outer class, but still - what is the difference between final and effectively final?

like image 469
alex Avatar asked Jan 05 '14 19:01

alex


People also ask

Should be final or effectively final Java?

Variables used in lambda should be final or effectively final. . On further research using SO forums and blog I learned that Java 8 has new concept called “Effectively final” variable. It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”.

What is effectively final in Java 8?

An effectively final variable is a variable whose value is never changed, but it isn't declared with the final keyword.

What is the difference between static final and final?

The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed.

What is the meaning of final method?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .


1 Answers

... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

For example, suppose that the variable numberLength is not declared final, and you add the marked assignment statement in the PhoneNumber constructor:

public class OutterClass {      int numberLength; // <== not *final*    class PhoneNumber {      PhoneNumber(String phoneNumber) {         numberLength = 7;   // <== assignment to numberLength         String currentNumber = phoneNumber.replaceAll(             regularExpression, "");         if (currentNumber.length() == numberLength)             formattedPhoneNumber = currentNumber;         else             formattedPhoneNumber = null;      }    ...    }  ...  } 

Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:

http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html

http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

like image 97
Suresh Atta Avatar answered Oct 01 '22 13:10

Suresh Atta