Is java (compiler or jvm) handling the static final members of a class differently? If so, how

It seems logical to do some optimization around static final constants (e.g. replace the variable with literals, etc.) to improve performance

+3
source share
3 answers

For built-in constants (strings, numbers), the compiler behaves differently, yes.

When the compiler sees a constant expression, it inserts the result of this constant expression into the code it uses, and does not evaluate it every time. So, if you have:

public static final int FOO = 10;
public static final int BAR = 5;

...
System.out.println(FOO * BAR);

then a constant value of 50 will be directly embedded in the code.

, - FOO BAR, , , ... "", -.

+8

, javac (, static final String): "" .

, , , , ....

+1

Yes, static end primitives are replaced with inline in compiled bytecode. This can be a source of problems, because if this constant changes, all the source files that need it (and not just the one declared in it) must be recompiled.

+1
source

Source: https://habr.com/ru/post/1764435/


All Articles