3

I always thought that class loading and class initialization are synonymous and usually happens on demand when the class being initialized/loaded is used in some way or the other for the first time. But now I know from this answer on SO regarding the behavior of final static fileds that holds compile time constants that my belief is wrong.

Please note the following which makes it quite clear that class loading and initialization are two different mechanism.

As a side point, please note the distinction between class loading and class initialization: only the latter's occurrence is precisely specified by the JLS. Class loading can happen at any time.

But can someone please explain the difference between class loading and class initialization in Java language. Normally intuition says that initialization should always be preceded by loading but I am be completely wrong. Can initialization ever happen without a class getting loaded?

Community
  • 1
  • 1
Geek
  • 26,489
  • 43
  • 149
  • 227

1 Answers1

8

From Java Virtual Machine Specification, Chapter 5. Loading, Linking, and Initializing , you can find this info (emphasys mine):

5.5. Initialization

Prior to initialization, a class or interface must be linked, that is, verified, prepared, and optionally resolved.

Going backwards to the Linking section

5.4. Linking

Linking a class or interface involves verifying and preparing that class or interface, its direct superclass, its direct superinterfaces, and its element type (if it is an array type), if necessary. Resolution of symbolic references in the class or interface is an optional part of linking. This specification allows an implementation flexibility as to when linking activities (and, because of recursion, loading) take place, provided that all of the following properties are maintained:

  • A class or interface is completely loaded before it is linked

So, we can infer that a class or interface must be loaded before being initialized.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • "Resolution of `symbolic references` in the class or interface is an optional part of linking." Can you explain this please? – Geek Sep 30 '13 at 17:36