Effectively Final

Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

When do we say that a variable is effectively final?

Variables and method parameters are said to be effectively final if they are not changed after initialization. Let us look at an example to understand this better.

public static void print(int i, int j) {
	String s ="Hello";
	System.out.println(s + " World");

In the above example, the variable i is effectively final, as it is not modified after initialization. The variable j is being incremented later, hence it is not effectively final. The String s is initialized to “Hello”. Later “World” is concatenated. However, this is not assigned to the variable s and hence s is also effectively final.

Checking if a variable is Effectively Final

To check if a variable will be considered as Effectively Final, simply add the final keyword before it. If it compiles without errors, it means that the variable is effectively final.

Significance of being Effectively Final

There are two rules that consider variables/method parameters only if they are effectively final.

  1. Method parameters and local variables are allowed to be referenced from lambda expressions only if they are effectively final, as demonstrated below.
public class EffFin1 {
		private static int age;
		public static void print(String name) {
			String address = "Address1";
			Consumer<String> consumer = s -> System.out.println("Name " + name + " Address " + address + " Age is " + age);

Here, the variables age, name and address can be used in the lambda expression as they are effectively final.

2. Resources declared earlier can be used in the try-with-resources statement, provided they are marked final or effectively final.

Path path= // Initialize path here
var writer = Files.newBufferedWriter(path);
try (writer) {
	writer.append(" Hello ");

In the above example, the variable writer is declared prior to the try-with-resources statement. Yet, it can be used here as it is effectively final.

Leave a Reply

Your email address will not be published. Required fields are marked *