Why is it mandatory to initialize a final variable when an instance is built?

Asked

Viewed 295 times

-1

In a certification review, I came across the following code:

public class Initializer {
    static int si = 10;
    int i;
    final boolean bool; 
}

It generates build error in variable declaration final boolean bool, because this one hasn’t been initialized. Note that the variable int i also not initialized, but there is no problem, because the instance variables (not final?) are initialized implicitly.

But then, why is there this differentiation with final and it is mandatory to initialize a final variable when an instance is built?

1 answer

0

Simply the final variable modifier serves to make it immutable, so in order for it to be immutable it must have its value initialized in the command in which it is declared or in the class constructor.

In java all variables are initialized with their default values even if it is null, so if the final variable were initialized with a default value it would be useless because it is immutable is not able to have its value modified.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.