It will be called at each iteration if the compiler / optimizer does not decide that it has no side effects and can eliminate the call as an optimization.
I mean, the compiler cannot just blindly store the value, because a function in java, unlike a mathematical function, can have not only a return value, but also side effects such as printing something into some stream or change of any global state, etc.
There is another reason that the compiler cannot omit the call of each iteration. The fact that your function does not accept any arguments does not mean that it will necessarily return the same value each time. It can, for example, enter a number from a stream and return it, or it can randomly generate a number.
Therefore, the compiler must be very careful before it can safely eliminate calls. So, if a function is expensive, you should definitely keep its value.
source share