Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nulling out final variable [duplicate]

Tags:

java

null

final

Why is the following code possible? (Just an example I just came up with while working on other code)

public String getLogIdentifierFromFile(final File file) {
    //this.file = null; //Gives compiler error as obviously expected
    nullify(file);
    return "";
}

public void nullify(Object object) {
    object = null;
}

And how can I ensure that the final from the top function actually has an effect? This time it is me making the nullify method, but it can also be anyone's code that my method needs to call.

like image 850
skiwi Avatar asked Nov 13 '13 10:11

skiwi


People also ask

Can a final variable be null?

Yes! You can initialize a blank final variable in constructor or instance initialization block.

Can we modify final variable in Java?

1) Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant).

What happens if I write final keyword just prefix of any method?

If you prefix a class definition with final , you prevent anyone from subclassing that class. Value types don't support inheritance so it doesn't make sense to mark a struct or enum as final . The final keyword communicates to the compiler that the class cannot and should not be subclassed.

What happens if the variable is final?

Final variables If a variable is declared with the final keyword, its value cannot be changed once initialized.


1 Answers

The code doesn't do what you think it does.

final applies to the reference. Your code nulls out a non-final copy of the original final reference. The copy is taken when you call nullify().

If you examine file after calling nullify(), you will observe that it remains unchanged.

Thus, this isn't a loophole in how final works.

like image 169
NPE Avatar answered Oct 10 '22 09:10

NPE