Be aware: Constants get inlined at compile time


Most books tell you that new String(“value”) should not be used since it creates two objects although only one is needed. But what the books almost never tell you is that there is one case in which you should use it: Java constants aka “public static final”.The reason for this is that constants (Strings or primitive types) get inlined by the compiler at compile time. This means that the value of the constant is not resolved when the class is loaded but copied when the sources are compiled. If you’re not using new String(…) you have to recompile all of your code otherwise there’s no guarantee that you code runs as expected.

This gets even more important if your code is not used exclusivly by you but provided as a 3rd party lib. Dozens of programs might be broken after an updte just because a constant has been changed.

,

  1. #1 by Polprav on October 23, 2009 - 6:30 am

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

(will not be published)

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 1,915 bad guys.