RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Intermediate
Jan 7, 2009



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Using the Final Keyword in Java

Contrary to popular opinion, the compiler cannot safely inline methods that have been declared as final. This is because these methods may have non-final declarations at runtime.

For example, suppose the compiler looks at class A, subclass B, and sub-subclass C. It sees a final method in A which it inlines into C. But at runtime, the versions loaded for A and B are different—the method is not final in A and it's overridden in B. Finally, C uses the incorrectly inlined version. This is due to a bug in some early compilers with the -O option. Thus, tips suggesting using either final or the -O option are not valid.

Conversely, final methods can be inlined after you've loaded them into the JVM. Because at that point the JVM knows definitely that the method is final. Compilers that operate after class loading, such as JIT compilers, are able to take advantage of final methods. Consequently, methods declared as final may have some performance benefit.

Generally, don't go out of your way to declare a method or class final purely for performance reasons. Only after you've definitely identified a performance problem is this even worth considering.

On the other hand, final variables, especially static final variables, are well worth using as standard.

Ashu Passi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date