Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Java 'final' keyword actually improve security?

Tags:

While there are many reasons to use the 'final' keyword in Java, one of the ones I keep hearing over and over again is that it makes your code more secure. While this seems to make sense in this trivial case:

public class Password {     public final String passwordHash;     ... } 

With the final keyword, you would expect that no malicious code would be able to change the variable passwordHash. However, using reflection it is possible to change the final modifier on the passwordHash field.

So does 'final' provide any real security, or is it just placebo?

Edit: There is some really interesting discussion, and I wish I could accept more than one answer. Thanks everyone for your input.

like image 394
Andres Avatar asked Jan 21 '10 18:01

Andres


People also ask

Does use of final keyword in Java improve the performance?

The final keyword has a different purpose when applied to classes and methods. When we apply the final keyword to a class, then that class cannot be subclassed. When we apply it to a method, then that method cannot be overridden. There are no reported performance benefits of applying final to classes and methods.

What is the advantage of using final keyword in Java?

Final Method in Java The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the Final Method is to declare methods of how's definition can not be changed by a child or subclass that extends it. The above example of the Final Method generates a compile-time error.

Why is the final modifier important to security in Java?

When a final modifier is used with a class then the class cannot be extended further. This is one way to protect your class from being subclassed and often sensitive classes are made final due to security reasons. This is also one of the reasons why String and wrapper classes are final in Java.

Should I use Final in Java?

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.


1 Answers

It's not 'security' in the sense of 'withstanding an attack'; it's more like 'harder to mess up by mistake'.

I prefer the word 'safety' as I feel it's more like preventing an accident, not malice.

like image 169
Javier Avatar answered Sep 18 '22 16:09

Javier