I'm learning about Java constants and I want to know when exactly is the space allocated in memory for a constant. Is it at compile time or runtime? For ex I have a constant like this:
public static final int NUMBER = 5;
I know that for an instance or class variable the space is allocated in memory at runtime, for an instance variable the space is allocated in memory when an object is created, and for a class variable the moment is when the class is loaded. But what's happening for a constant? I know the compiler do some optimization when it finds this constant and replaces every the constant name everywhere in the code with its value. But when exactly is the space allocated in memory for this constant NUMBER? At compile time or runtime?
Memory allocation could never happen at compile-time, since compiling produces only the byte-code and never ever allocates any memory for run-time. Memory allocation at compile-time would result in a memory leak. You would never know when to release the memory (halting-problem / will I ever use this again?). Maybe what you mean: while compiling, the compiler substitutes (as you state) your identifier with the literal / value of the "constant".