How JVM starts looking for classes?

How classes are found. Answer is here:

http://docs.oracle.com/javase/1.5.0/docs/tooldocs/findingclasses.html

Answer for point 2: Order of finding classes is as follows:

  1. classes or packages in current directory.
  2. classes found from CLASSPATH environment variable. [overrides 1]
  3. classes found from -classpath command line option. [overrides 1,2]
  4. classes found from jar archives specified via -jar command line option [overrides 1,2,3]

So if you use -jar option while running, classes come from jarfile.

Only one class is loaded though.


Without using any additional classloader:

  • Search order for a JVM:
    1. Runtime classes (basically, rt.jar in $JRE_HOME/lib`)
    2. Extension classes (some JARs in $JRE_HOME/lib/ext`)
    3. Classpath, in order. There are four possibilities for specifying classpath:
      1. If -jar was specified, then that JAR is in the classpath. Whatever classpath is declared as classpath in META-INF/MANIFEST.MF is also considered.
      2. Else, if -cp was specified, that is the classpath.
      3. Else, if $CLASSPATH is set, that is the classpath.
      4. Else, the current directory from which java has been launched is the classpath.
      So, if I specify -cp src/A.jar:src/B.jar, then A.jar will be searched first, then B.jar
  • The JVM loads only the class that is found first, according to the order in which the directories/JARs are declared in the classpath. This is important if you use -cp or $CLASSPATH.
  • In single thread scenarios and with recent JVMs, Vector and ArrayList should have similar performance (ArrayList should perform slightly better as it is not synchronized, but locking is fast currently when there is no contention, so the difference should be small). Anyway, Vector is obsolete: don't use it in new code.