P
P
Pavel Chechko2020-12-30 20:02:13
Java
Pavel Chechko, 2020-12-30 20:02:13

What happens when you access static constants?

For example:

public class Solution {
  static final int С = 55 + 10;
  static final int A = 55 + 10;
}

class Solution2 {
  public static void main(String[] args) {
    System.out.println(Solution.C);
  }
}


I know that the Solution class has not been loaded into RAM and initialized. From here questions:
1. Have all class constants Solutionbeen loaded into the pool of constants, or only C?
2. When you re-access to, Solution.Cwill it be checked if it is in the constant pool, and if so, is the already initialized value taken from there?

Or how does it all happen?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-12-30
@Etikoriya

Firstly, the compiler will fold the constants, so there will be no addition in the class file, Cand Athey will be equal to 65. Secondly, when accessing any static field, the class will be fully loaded into metaspace and the constant pool will be fully initialized.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question